List of usage examples for javax.mail.internet MimeMessage saveChanges
@Override public void saveChanges() throws MessagingException
From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java
@Override public void sendMail(MimeMessage msg, String username, String password) throws ApsSystemException { //WebMailConfig config = this.getConfig(); String smtpUsername = this.checkSmtpAuthUsername(username); String smtpPassword = this.checkSmtpAuthUserPassword(password); //String smtpUsername = (config.isSmtpEntandoUserAuth()) ? username : config.getSmtpUserName(); //String smtpPassword = (config.isSmtpEntandoUserAuth()) ? password : config.getSmtpPassword(); //Session session = this.createSession(true, smtpUsername, smtpPassword); Session session = (msg instanceof JpMimeMessage) ? ((JpMimeMessage) msg).getSession() : this.createSession(true, smtpUsername, smtpPassword); Transport bus = null;/*from w w w .j av a 2 s . co m*/ try { bus = session.getTransport("smtp"); //StringUtils.isEmpty(bus) if (StringUtils.isBlank(smtpUsername) && StringUtils.isBlank(smtpPassword)) { bus.connect(); } /* if ((smtpUsername != null && smtpUsername.trim().length()>0) && (smtpPassword != null && smtpPassword.trim().length()>0)) { if (port != null && port.intValue() > 0) { bus.connect(config.getSmtpHost(), port.intValue(), smtpUsername, smtpPassword); } else { bus.connect(config.getSmtpHost(), smtpUsername, smtpPassword); } } else { bus.connect(); } */ //bus.connect(); msg.saveChanges(); bus.send(msg); } catch (Throwable t) { _logger.error("Error sending mail", t); //ApsSystemUtils.logThrowable(t, this, "sendMail", "Error sending mail"); throw new ApsSystemException("Error sending mail", t); } finally { closeTransport(bus); } }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testEncryptBase64EncodeBug() throws Exception { MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setSubject("test"); message.setContent("test", "text/plain"); SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from"); X509Certificate certificate = TestUtils .loadCertificate("test/resources/testdata/certificates/certificate-base64-encode-bug.cer"); builder.addRecipient(certificate, SMIMERecipientMode.ISSUER_SERIAL); builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC); MimeMessage newMessage = builder.buildMessage(); newMessage.saveChanges(); File file = new File(tempDir, "testEncryptBase64EncodeBug.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); newMessage.writeTo(new SkipHeadersOutputStream(bos)); String blob = new String(bos.toByteArray(), "us-ascii"); // check if all lines are not longer than 76 characters LineIterator it = IOUtils.lineIterator(new StringReader(blob)); while (it.hasNext()) { String next = it.nextLine(); if (next.length() > 76) { fail("Line length exceeds 76: " + next); }/*from w ww . ja v a2 s. c om*/ } }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.//www .jav a 2 s. com * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testEncryptSignedQuotedPrintableSoftBreaksDirectBC() throws Exception { MimeMessage message = loadMessage("qp-soft-breaks-signed.eml"); SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator(); JceKeyTransRecipientInfoGenerator infoGenerator = new JceKeyTransRecipientInfoGenerator( encryptionCertificate);//from w w w . java 2s. co m envelopedGenerator.addRecipientInfoGenerator(infoGenerator); JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder( new ASN1ObjectIdentifier("1.2.840.113549.3.7"), 0).setProvider("BC"); MimeBodyPart bodyPart = envelopedGenerator.generate(message, encryptorBuilder.build()); MimeMessage newMessage = new MimeMessage(MailSession.getDefaultSession()); newMessage.setContent(bodyPart.getContent(), bodyPart.getContentType()); newMessage.saveChanges(); File file = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage)); File opensslOutputFileSigned = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl-signed.eml"); decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned); newMessage = MailUtils.loadMessage(opensslOutputFileSigned); assertTrue(newMessage.isMimeType("multipart/signed")); File opensslOutputFile = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl.eml"); verifyMessage(opensslOutputFileSigned, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("text/plain")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from www .j av a 2s.c o m * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/* w w w .ja v a2 s . c o m*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from ww w. java 2s . c om props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:eu.scape_project.planning.application.BugReport.java
/** * Method responsible for sending a bug report per mail. * /*from w w w .j a v a2 s. c o m*/ * @param userEmail * email address of the user. * @param errorDescription * error description given by the user. * @param exception * the exception causing the bug/error. * @param requestUri * request URI where the error occurred * @param location * the location of the application where the error occurred * @param applicationName * application name * @param plan * the plan where the exception occurred * @throws MailException * if the bug report could not be sent */ public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri, String location, String applicationName, Plan plan) throws MailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback"))); message.setSubject("[" + applicationName + "] from " + location); StringBuilder builder = new StringBuilder(); // Date builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n"); // User info if (user == null) { builder.append("No user available.\n\n"); } else { builder.append("User: ").append(user.getUsername()).append("\n"); if (user.getUserGroup() != null) { builder.append("Group: ").append(user.getUserGroup().getName()).append("\n"); } } builder.append("UserMail: ").append(userEmail).append("\n\n"); // Plan if (plan == null) { builder.append("No plan available.").append("\n\n"); } else { builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n"); builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n"); } // Description builder.append("Description:\n"); builder.append(SEPARATOR_LINE); builder.append(errorDescription).append("\n"); builder.append(SEPARATOR_LINE).append("\n"); // Request URI builder.append("Request URI: ").append(requestUri).append("\n\n"); // Exception if (exception == null) { builder.append("No exception available.").append("\n"); } else { builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n"); builder.append("Exception message: ").append(exception.getMessage()).append("\n"); StringWriter writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); builder.append("Stacktrace:\n"); builder.append(SEPARATOR_LINE); builder.append(writer.toString()); builder.append(SEPARATOR_LINE); } message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(), config.getString("mail.feedback")); String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."; Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO", userMessage, user); try { utx.begin(); em.persist(notification); utx.commit(); } catch (Exception e) { log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e); } } catch (MessagingException e) { throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to " + config.getString("mail.feedback"), e); } }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private MimeMessage createMessage(Mail mail, Collection<MailAddress> recipients, PasswordContainer passwordContainer) throws MessagingException, MissingRecipientsException, TemplateException, IOException { Check.notNull(passwordContainer, "passwordContainer"); SimpleHash root = new SimpleHash(); root.put(PASSWORD_CONTAINER_TEMPLATE_PARAM, passwordContainer); /*// ww w . j a v a 2 s . c om * Note: although passwordID can be retrieved from passwordContainer we keep passwordID to make sure * that existing templates that use passwordID are still working */ root.put(PASSWORD_ID_TEMPLATE_PARAM, passwordContainer.getPasswordID()); /* * We should put the real recipient(s) in the Freemarker root. bug https://jira.djigzo.com/browse/GATEWAY-38. */ root.put(RECIPIENTS_TEMPLATE_PARAM, recipients); /* * Get the Reply-To of the message and validate. * * Note: the Reply-To is not canonicalized because that can result in invalid email addresses. For example * "email with space"@example.com is only valid with the quotes. */ String replyTo = EmailAddressUtils.validate(EmailAddressUtils.getEmailAddress( EmailAddressUtils.getAddress(EmailAddressUtils.getReplyToQuietly(mail.getMessage())))); /* * The ReplySettings will be placed in the context since they are needed in #getTemplateFromUser to * get the reply URL */ ReplySettings replySettings = new ReplySettings(mail.getMessage().getSubject(), recipients, replyTo); getActivationContext().set(REPLY_SETTINGS_ACTIVATION_CONTEXT_KEY, replySettings); /* * Create a message from a template. * * Note: Calling createMessage will result in a call to #getTemplateFromUser */ MimeMessage containerMessage = createMessage(mail, root); /* * The call to createMessage should result in the reply URL to be set (if reply is allowed and all * required settings are set) */ String replyURL = replySettings.getReplyURL(); /* * Copy all non content headers from source to notificationMessage. */ HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(new ContentHeaderNameMatcher()); HeaderUtils.copyHeaders(mail.getMessage(), containerMessage, nonContentMatcher); /* * Create PDF from the source message */ ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); MessagePDFBuilder pdfBuilder = new MessagePDFBuilder(); pdfBuilder.setFontProvider(fontProvider); if (viewerPreferences != null) { pdfBuilder.setViewerPreference(viewerPreferences); } try { pdfBuilder.buildPDF(mail.getMessage(), replyURL, pdfStream); } catch (DocumentException e) { throw new MessagingException("Error building PDF.", e); } catch (IOException e) { throw new MessagingException("Error building PDF.", e); } byte[] unencryptedPDF = pdfStream.toByteArray(); byte[] encryptedPdf; try { String userPassword = passwordContainer.getPassword(); String ownerPassword = getOwnerPassword(userPassword); encryptedPdf = encryptPDF(unencryptedPDF, userPassword, ownerPassword); } catch (IOException e) { throw new MessagingException("Error encrypting PDF.", e); } catch (DocumentException e) { throw new MessagingException("Error encrypting PDF.", e); } catch (EncryptorException e) { throw new MessagingException("Unable to retrieve password.", e); } /* * Now find and replace the pdf inside the notificationMessage with the encrypted pdf */ addEncryptedPDF(containerMessage, encryptedPdf); containerMessage.saveChanges(); String messageID = null; if (retainMessageID) { messageID = StringUtils.trimToNull(mail.getMessage().getMessageID()); } if (messageID == null) { messageID = MessageIDCreator.getInstance().createUniqueMessageID(); } containerMessage = new MimeMessageWithID(containerMessage, messageID); return containerMessage; }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./*from www .j a v a2s . c o m*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }