List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java
/** * Sends email with attachments//from www .j a v a2 s . co m * * @param from * The address this message is to be listed as coming from. * @param to * The address(es) this message should be sent to. * @param subject * The subject of this message. * @param content * The body of the message. * @param headerToStr * If specified, this is placed into the message header, but "to" is used for the recipients. * @param replyTo * If specified, this is the reply to header address(es). * @param additionalHeaders * Additional email headers to send (List of String). For example, content type or forwarded headers (may be null) * @param messageAttachments * Message attachments */ protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject, String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<EmailAttachment> emailAttachments) { if (testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments); return; } if (smtp == null || smtp.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMailWithAttachments: smtp not set"); } return; } if (from == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: from is needed to send email"); } return; } if (to == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: to is needed to send email"); } return; } if (content == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: content is needed to send email"); } return; } if (emailAttachments == null || emailAttachments.size() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMail: emailAttachments are needed to send email with attachments"); } return; } try { if (session == null) { if (logger.isWarnEnabled()) { logger.warn("mail session is null"); } return; } MimeMessage message = new MimeMessage(session); // default charset String charset = "UTF-8"; message.setSentDate(new Date()); message.setFrom(from); message.setSubject(subject, charset); MimeBodyPart messageBodyPart = new MimeBodyPart(); // Content-Type: text/plain; text/html; String contentType = null, contentTypeValue = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith("content-type:")) { contentType = header; contentTypeValue = contentType.substring( contentType.indexOf("content-type:") + "content-type:".length(), contentType.length()); break; } } } // message String messagetype = ""; if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(content, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(content, messagetype); } //messageBodyPart.setContent(content, "text/html; charset="+ charset); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); String jforumAttachmentStoreDir = serverConfigurationService() .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR); if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR + ") property is not set in sakai.properties "); } } else { // attachments for (EmailAttachment emailAttachment : emailAttachments) { String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(emailAttachment.getRealFileName()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("Error while attaching attachments: " + e, e); } } } } message.setContent(multipart); Transport.send(message, to); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("sendMail: Error in sending email: " + e, e); } } }
From source file:org.silverpeas.core.mail.TestSmtpMailSending.java
@Test public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues() throws Exception { MailAddress senderEmail = MailAddress.eMail(COMMON_FROM); MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name"); String subject = "A subject"; Multipart content = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE); content.addBodyPart(mimeBodyPart);//from w w w . j a v a 2 s. co m MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject) .withContent(content); // Sending mail mailSending.sendSynchronously(); // Verifying sent data MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend; assertThat(mailToSend.getFrom(), is(senderEmail)); assertThat(mailToSend.getTo(), hasItem(receiverEmail)); assertThat(mailToSend.getSubject(), is(subject)); assertThat(mailToSend.getContent().isHtml(), is(true)); assertThat(mailToSend.getContent().toString(), is(content.toString())); assertThat(mailToSend.isReplyToRequired(), is(false)); assertThat(mailToSend.isAsynchronous(), is(false)); assertMailSent(mailToSend); }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * //w w w . j a v a2s . c o m * @param message * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.tizzit.util.mail.Mail.java
/** * Creates an attachment containing the specified file. * /* ww w. ja va2 s .c om*/ * @param fileNameWithPath the absolute file name */ public void addAttachmentFromFile(String fileNameWithPath) { try { File file = new File(fileNameWithPath); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.attachFile(file); if (this.tempFileNameMappings.containsKey(fileNameWithPath)) { bodyPart.setFileName(this.tempFileNameMappings.get(fileNameWithPath)); } this.attachments.add(bodyPart); } catch (IOException exception) { log.error("Error opening file " + fileNameWithPath, exception); } catch (MessagingException exception) { log.error("Error creating attachment comprising file " + fileNameWithPath); } }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *//*from www . j ava2 s . c om*/ public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *//*from w w w. java 2s . c o m*/ private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); if (MULTIPART.equals(contentType.getBaseType())) { MimeMultipart nested = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return entity.asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return entityContentType; } @Override public String getName() { return null; } }); dataPart.setContent(nested, contentType.getBaseType()); } else { dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); } dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public void addAttachement(File file) { try {/*from w w w. j a v a 2s . c o m*/ /* Check if email has already some contents. */ Object content; try { content = this.source.getContent(); } catch (IOException e) { /* If no content, then content is null.*/ content = null; log.warn("Email content is empty.", e); } if (content != null) { if (content instanceof String) { /* This message is not multipart yet. Change it to multipart. */ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText((String) this.source.getContent()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); this.source.setContent(multipart); } } else { /* No content, then create initial multipart content. */ Multipart multipart = new MimeMultipart(); this.source.setContent(multipart); } /* Get current content. */ Multipart multipart = (Multipart) this.source.getContent(); /* add attachment as a new part. */ MimeBodyPart attachementPart = new MimeBodyPart(); DataSource fileSource = new FileDataSource(file); DataHandler fileDataHandler = new DataHandler(fileSource); attachementPart.setDataHandler(fileDataHandler); attachementPart.setFileName(file.getName()); multipart.addBodyPart(attachementPart); } catch (Exception e) { throw new GmailException("Failed to add attachement", e); } }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeBodyPart????text/plain/*from w ww . ja v a2 s. c o m*/ * * @return MimeBodyParttext/plain? * @throws MessagingException */ private MimeBodyPart createTextPart() throws MessagingException { MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(text, charset); setHeaderToPart(textPart); return textPart; }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifyAccountDeleted(TemporaryMailContainer container) { try {//from w w w .j a va 2s . c o m Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject")); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart HTML message with the attachements associated to the * message and attached files. FIXME: use prepareMessage method * * @param strRecipientsTo//from ww w . jav a2 s. co m * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param urlAttachements * The List of UrlAttachement Object, containing the URL of * attachments associated with their content-location. * @param fileAttachements * The list of files attached * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty())) ? new MimeMultipart(MULTIPART_RELATED) : new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); if (urlAttachements != null) { ByteArrayDataSource urlByteArrayDataSource; for (UrlAttachment urlAttachement : urlAttachements) { urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement); if (urlByteArrayDataSource != null) { msgBodyPart = new MimeBodyPart(); // Fill this part, then add it to the root part with the // good headers msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource)); msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation()); multipart.addBodyPart(msgBodyPart); } } } // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }