List of usage examples for javax.mail.internet MimeMultipart addBodyPart
@Override public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.apache.synapse.transport.mail.MailTransportSender.java
/** * Populate email with a SOAP formatted message * @param outInfo the out transport information holder * @param msgContext the message context that holds the message to be written * @throws AxisFault on error//from w w w .j ava 2 s .c o m */ private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new BaseTransportException("Unable to get the message formatter to use"); } WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] { smtpFromAddress }); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // if a custom message id is set, use it if (msgContext.getMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body ByteArrayOutputStream baos = null; String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); DataHandler dataHandler = null; MimeMultipart mimeMultiPart = null; OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement(); if (firstChild != null) { if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) { baos = new ByteArrayOutputStream(); OMNode omNode = firstChild.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { dataHandler = (DataHandler) dh; } } } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) { if (firstChild instanceof OMSourcedElementImpl) { baos = new ByteArrayOutputStream(); try { firstChild.serializeAndConsume(baos); } catch (XMLStreamException e) { handleException("Error serializing 'text' payload from OMSourcedElement", e); } dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), MailConstants.TEXT_PLAIN); } else { dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN); } } else { baos = new ByteArrayOutputStream(); messageFormatter.writeTo(msgContext, format, baos, true); // create the data handler dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), contentType); String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } } } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); } catch (MessagingException e) { handleException("Error creating mail message or sending it to the configured server", e); } finally { try { if (baos != null) { baos.close(); } } catch (IOException ignore) { } } }
From source file:org.chenillekit.mail.services.TestMailService.java
@Test public void test_multipartemail_sending() throws EmailException, MessagingException { MultiPartEmail email = new MultiPartEmail(); email.setSubject("Test Mail 2"); email.addTo("homburgs@gmail.com"); email.setFrom("homburgs@gmail.com"); email.setMsg("This is a dummy message text!"); email.addPart("This is a dummy message part 1!", "text/plain"); MimeMultipart mmp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText("This is a dummy MimeBodyPart 1!"); mmp.addBodyPart(mbp); email.addPart(mmp);//ww w . jav a 2s . c o m EmailAttachment attachment = new EmailAttachment(); attachment.setDescription("dummy.txt"); attachment.setURL(new ClasspathResource("dummy.txt").toURL()); email.attach(attachment); MailService mailService = registry.getService(MailService.class); boolean sended = mailService.sendEmail(email); assertTrue(sended, "sended"); }
From source file:org.eclipse.ecr.automation.core.mail.Composer.java
public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType, List<Blob> attachments) throws Exception { if (textType == null) { textType = "plain"; }/*from w w w . ja va2s . co m*/ Mailer.Message msg = mailer.newMessage(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); String result = render(templateContent, ctx); body.setText(result, "UTF-8", textType); mp.addBodyPart(body); for (Blob blob : attachments) { MimeBodyPart a = new MimeBodyPart(); a.setDataHandler(new DataHandler(new BlobDataSource(blob))); a.setFileName(blob.getFilename()); mp.addBodyPart(a); } msg.setContent(mp); return msg; }
From source file:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }/*from ww w . j a va 2 s. co m*/ Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // Optional : You can also set your custom headers in the Email if you // Want // msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>/*w ww .ja v a2 s . co m*/ * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }
From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java
/** * /*ww w .j a v a 2 s . c o m*/ * @param invitedUsersList */ private void invitedUserNotification(Map<String, List<Space>> invitedUsersList) { for (Map.Entry<String, List<Space>> entry : invitedUsersList.entrySet()) { try { String userId = entry.getKey(); List<Space> spacesList = entry.getValue(); Locale locale = Locale.getDefault(); // get default locale of the manager String userLocale = this.getOrganizationService().getUserProfileHandler() .findUserProfileByName(userId).getAttribute("user.language"); Profile userProfile = getIdentityManager() .getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false).getProfile(); if (userLocale != null && !userLocale.trim().isEmpty()) { locale = new Locale(userLocale); } // getMessageTemplate MessageTemplate messageTemplate = this.getMailMessageTemplate( SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_INVITATIONS, locale); GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject()); Map binding = new HashMap(); binding.put("userProfile", userProfile); binding.put("portalUrl", this.getPortalUrl()); binding.put("invitationUrl", this.getPortalUrl() + "/portal/intranet/invitationSpace"); binding.put("spacesList", spacesList); String subject = g.render(binding); g = new GroovyTemplate(messageTemplate.getHtmlContent()); String htmlContent = g.render(binding); g = new GroovyTemplate(messageTemplate.getPlainTextContent()); String textContent = g.render(binding); MailService mailService = this.getMailService(); Session mailSession = mailService.getMailSession(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(this.getSenderAddress()); // send email to invited user message.setRecipient(RecipientType.TO, new InternetAddress(userProfile.getEmail(), userProfile.getFullName())); message.setSubject(subject); MimeMultipart content = new MimeMultipart("alternative"); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textContent); html.setContent(htmlContent, "text/html; charset=ISO-8859-1"); content.addBodyPart(text); content.addBodyPart(html); message.setContent(content); log.info("Sending mail to : " + userProfile.getEmail() + " : " + subject + "\n" + html); mailService.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java
/** * /* w w w .ja va 2 s .c o m*/ * @param space * @param managers * @param pendingUsers */ private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) { //TODO : use groovy template stored in JCR for mail information (cleaner, real templating) log.info("Sending mail to space manager : pending users"); try { // loop on each manager and send mail // like that each manager will have the mail in its preferred language // ideally should be done in a different executor // TODO: see if we can optimize this to avoid do it for all user // - send a mail to all the users in the same time (what about language) // - cache the template result and send mail for (Profile manager : managerList) { Locale locale = Locale.getDefault(); // get default locale of the manager String userId = manager.getIdentity().getRemoteId(); String userLocale = this.getOrganizationService().getUserProfileHandler() .findUserProfileByName(userId).getAttribute("user.language"); if (userLocale != null && !userLocale.trim().isEmpty()) { locale = new Locale(userLocale); } // getMessageTemplate MessageTemplate messageTemplate = this.getMailMessageTemplate( SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale); GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject()); String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl() + "/settings"; //TODO: see which API to use String spaceAvatarUrl = null; if (space.getAvatarUrl() != null) { spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl(); } Map binding = new HashMap(); binding.put("space", space); binding.put("portalUrl", this.getPortalUrl()); binding.put("spaceSettingUrl", spaceUrl); binding.put("spaceAvatarUrl", spaceAvatarUrl); binding.put("userPendingList", pendingUsers); String subject = g.render(binding); g = new GroovyTemplate(messageTemplate.getHtmlContent()); String htmlContent = g.render(binding); g = new GroovyTemplate(messageTemplate.getPlainTextContent()); String textContent = g.render(binding); MailService mailService = this.getMailService(); Session mailSession = mailService.getMailSession(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(this.getSenderAddress()); // send email to manager message.setRecipient(RecipientType.TO, new InternetAddress(manager.getEmail(), manager.getFullName())); message.setSubject(subject); MimeMultipart content = new MimeMultipart("alternative"); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textContent); html.setContent(htmlContent, "text/html; charset=ISO-8859-1"); content.addBodyPart(text); content.addBodyPart(html); message.setContent(content); log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html); //mailService.sendMessage(message); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }//w w w . j a va 2 s .c o m if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getBcc() != null) { message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); textBodyPart.setHeader("Content-Transfer-Encoding", "base64"); textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\""); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64"); htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\""); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:org.igov.io.mail.MailOld.java
public MailOld _PartHTML() throws MessagingException, EmailException { // init(); LOG.info("_PartHTML"); //oMultiPartEmail.setMsg("0"); MimeMultipart oMimeMultipart = new MimeMultipart("related"); BodyPart oBodyPart = new MimeBodyPart(); oBodyPart.setContent(getBody(), "text/html; charset=\"utf-8\""); oMimeMultipart.addBodyPart(oBodyPart); oMultiPartEmail.setContent(oMimeMultipart); LOG.info("(getBody()={})", getBody()); return this; }
From source file:org.igov.io.mail.MailOld.java
public MailOld _Part(DataSource oDataSource) throws MessagingException, EmailException { // init(); LOG.info("_Part"); MimeMultipart oMimeMultipart = new MimeMultipart("related"); BodyPart oBodyPart = new MimeBodyPart(); oBodyPart.setContent(oDataSource, "application/zip"); oMimeMultipart.addBodyPart(oBodyPart); return this; }