List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart(DataSource ds) throws MessagingException
From source file:au.aurin.org.controller.RestController.java
public Boolean sendEmail(final String randomUUIDString, final String password, final String email, final List<String> lstApps, final String fullName) throws IOException { final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString; logger.info("Starting sending Email to:" + email); String msg = ""; if (!fullName.equals("")) { msg = msg + "Dear " + fullName + "<br>"; }/*from w w w . j a va 2 s . c om*/ Boolean lswWhatIf = false; if (lstApps != null) { //msg = msg + "You have been given access to the following applications: <br>"; msg = msg + "<br>You have been given access to the following applications: <br>"; for (final String st : lstApps) { if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) { lswWhatIf = true; } msg = "<br>" + msg + st + "<br>"; } } msg = msg + "<br>Your current password is : " + password + " <br> To customise the password please change it using link below: <br> <a href='" + clink + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. "; final String subject = "AURIN Workbench Access"; final String from = classmail.getFrom(); final String to = email; if (lswWhatIf == true) { msg = msg + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au"; msg = msg + "<br>For other related requests please contact one of the members of the project team."; msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The Online WhatIf team<br>"; msg = msg + "<br><strong>Prof Christopher Pettit</strong> Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)"; msg = msg + "<br><strong>Claudia Pelizaro</strong> Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)"; msg = msg + "<br><strong>Andrew Dingjan</strong> Director, AURIN (andrew.dingjan@unimelb.edu.au)"; msg = msg + "<br><strong>Serryn Eagleson</strong> Manager Data and Business Analytics (serrynle@unimelb.edu.au)"; } else { msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The AURIN Workbench team"; } try { final Message message = new MimeMessage(getSession()); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.addFrom(new InternetAddress[] { new InternetAddress(from) }); message.setSubject(subject); message.setContent(msg, "text/html"); ////////////////////////////////// final MimeMultipart multipart = new MimeMultipart("related"); final BodyPart messageBodyPart = new MimeBodyPart(); //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />"; //msg = msg + "<img src=\"cid:image\">"; messageBodyPart.setContent(msg, "text/html"); // add it multipart.addBodyPart(messageBodyPart); /////// second part (the image) // messageBodyPart = new MimeBodyPart(); final URL peopleresource = getClass().getResource("/logo.jpg"); logger.info(peopleresource.getPath()); // final DataSource fds = new FileDataSource( // peopleresource.getPath()); // // messageBodyPart.setDataHandler(new DataHandler(fds)); // messageBodyPart.setHeader("Content-ID", "<image>"); // // add image to the multipart // //multipart.addBodyPart(messageBodyPart); /////////// final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(peopleresource.getPath()); // final String cid = "1"; // imagePart.setContentID("<" + cid + ">"); imagePart.setHeader("Content-ID", "AbcXyz123"); imagePart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(imagePart); // put everything together message.setContent(multipart); //////////////////////////////// Transport.send(message); logger.info("Email sent to:" + email); } catch (final Exception mex) { logger.info(mex.toString()); return false; } return true; }
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>/*from ww w .j a va 2 s . c om*/ * <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.j2free.email.EmailService.java
private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body, ContentType contentType, Priority priority, boolean ccSender) throws AddressException, MessagingException, RejectedExecutionException { MimeMessage message = new MimeMessage(session); message.setFrom(from);/* w w w . j a v a 2s. co m*/ message.setRecipients(Message.RecipientType.TO, recipients); for (Map.Entry<String, String> header : headers.entrySet()) message.setHeader(header.getKey(), header.getValue()); // CC the sender if they want if (ccSender) message.addRecipient(Message.RecipientType.CC, from); message.setReplyTo(new InternetAddress[] { from }); message.setSubject(subject); message.setSentDate(new Date()); if (contentType == ContentType.PLAIN) { // Just set the body as plain text message.setText(body, "UTF-8"); } else { MimeMultipart multipart = new MimeMultipart("alternative"); // Create the text part MimeBodyPart text = new MimeBodyPart(); text.setText(new HtmlFilter().filterForEmail(body), "UTF-8"); // Add the text part multipart.addBodyPart(text); // Create the HTML portion MimeBodyPart html = new MimeBodyPart(); html.setContent(body, ContentType.HTML.toString()); // Add the HTML portion multipart.addBodyPart(html); // set the message content message.setContent(multipart); } enqueue(message, priority); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed signed part*/ public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); String signatureTransferEncoding = null; MimeMultipart checkPart = (MimeMultipart) signedPart.getContent(); //it is sure that it is a signed part: set the type to multipart if the //parser has problems parsing it. Don't know why sometimes a parsing fails for //MimeBodyPart. This check looks if the parser is able to find more than one subpart if (checkPart.getCount() == 1) { MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType)); MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null)); possibleSignedMessage.setContent(multipart, multipart.getContentType()); possibleSignedMessage.saveChanges(); //overwrite the formerly found signed part signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage); }/* w w w. j ava 2s .c o m*/ //get the content encoding of the signature MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent(); //body part 1 is always the signature String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding"); if (encodingHeader != null) { signatureTransferEncoding = encodingHeader[0]; } return (helper.verify(signedPart, signatureTransferEncoding, certificate)); }
From source file:com.sonicle.webtop.core.app.WebTopApp.java
public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts) throws MessagingException { //Session session=getGlobalMailSession(pid.getDomainId()); MimeMessage msg = new MimeMessage(session); try {//from ww w . java 2 s . c o m subject = MimeUtility.encodeText(subject); } catch (Exception exc) { } msg.setSubject(subject); msg.addFrom(new InternetAddress[] { from }); if (to != null) for (InternetAddress addr : to) { msg.addRecipient(Message.RecipientType.TO, addr); } if (cc != null) for (InternetAddress addr : cc) { msg.addRecipient(Message.RecipientType.CC, addr); } if (bcc != null) for (InternetAddress addr : bcc) { msg.addRecipient(Message.RecipientType.BCC, addr); } body = StringUtils.defaultString(body); MimeMultipart mp = new MimeMultipart("mixed"); if (rich) { MimeMultipart alternative = new MimeMultipart("alternative"); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8")); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)), MailUtils.buildPartContentType("text/plain", "UTF-8")); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } else { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8")); mp.addBodyPart(mbp1); } if (parts != null) { for (MimeBodyPart part : parts) mp.addBodyPart(part); } msg.setContent(mp); msg.setSentDate(new java.util.Date()); Transport.send(msg); }
From source file:com.sonicle.webtop.core.app.WebTopApp.java
public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, Collection<InternetAddress> to, Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, String body, Collection<MimeBodyPart> parts) throws MessagingException { MimeMultipart mp = new MimeMultipart("mixed"); body = StringUtils.defaultString(body); // Adds text parts from passed body if (rich) {/*from w w w . ja v a2 s. c o m*/ MimeMultipart alternative = new MimeMultipart("alternative"); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8")); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)), MailUtils.buildPartContentType("text/plain", "UTF-8")); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } else { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8")); mp.addBodyPart(mbp1); } // Adds remaining parts to the mixed one if (parts != null) { for (MimeBodyPart p : parts) { mp.addBodyPart(p); } } sendEmail(session, from, to, cc, bcc, subject, mp); }
From source file:org.liveSense.service.email.EmailServiceImpl.java
/** * {@inheritDoc}//www. j ava 2s . co m */ @Override public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject, Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc, HashMap<String, Object> variables) throws Exception { boolean haveSession = false; try { if (session != null && session.isLive()) { haveSession = true; } else { session = repository.loginAdministrative(null); } if (template == null) { throw new RepositoryException("Template is null"); } String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables); if (html == null) throw new RepositoryException("Template is empty"); // create the messge. MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null); MimeMultipart rootMixedMultipart = new MimeMultipart("mixed"); mimeMessage.setContent(rootMixedMultipart); MimeMultipart nestedRelatedMultipart = new MimeMultipart("related"); MimeBodyPart relatedBodyPart = new MimeBodyPart(); relatedBodyPart.setContent(nestedRelatedMultipart); rootMixedMultipart.addBodyPart(relatedBodyPart); MimeMultipart messageBody = new MimeMultipart("alternative"); MimeBodyPart bodyPart = null; for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) { BodyPart bp = nestedRelatedMultipart.getBodyPart(i); if (bp.getFileName() == null) { bodyPart = (MimeBodyPart) bp; } } if (bodyPart == null) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); nestedRelatedMultipart.addBodyPart(mimeBodyPart); bodyPart = mimeBodyPart; } bodyPart.setContent(messageBody, "text/alternative"); // Create the plain text part of the message. MimeBodyPart plainTextPart = new MimeBodyPart(); plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding()); messageBody.addBodyPart(plainTextPart); // Create the HTML text part of the message. MimeBodyPart htmlTextPart = new MimeBodyPart(); htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8 messageBody.addBodyPart(htmlTextPart); // Check if resource have nt:file childs adds as attachment if (resource != null && resource.hasNodes()) { NodeIterator iter = resource.getNodes(); while (iter.hasNext()) { Node n = iter.nextNode(); if (n.getPrimaryNodeType().isNodeType("nt:file")) { // Part two is attachment MimeBodyPart attachmentBodyPart = new MimeBodyPart(); InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary() .getStream(); String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString(); String fileName = n.getName(); DataSource source = new StreamDataSource(fileData, fileName, mimeType); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName(fileName); attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); attachmentBodyPart.setContentID(fileName); rootMixedMultipart.addBodyPart(attachmentBodyPart); } } } prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc, variables); sendEmail(session, mimeMessage); // } finally { if (!haveSession && session != null) { if (session.hasPendingChanges()) { try { session.save(); } catch (Throwable th) { } } session.logout(); } } }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java
/** * Sends an email to the given id including a link to the password page. The * link contains the refID./*from www. j ava 2s . c om*/ * * @param emailType * - refers to the email that shall be sent, 0 sends an email for * newly registered users, 1 sends a standard password-reset * email * @param emailaddress * @param refID * @return */ public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) { String salutation = ""; if (user.getGender().equalsIgnoreCase("male")) { salutation = "geehrter Herr " + user.getName(); } else { salutation = "geehrte Frau " + user.getName(); } MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"), emailProperties.getProperty("mail.user.password")); // Login Properties props = (Properties) emailProperties.clone(); props.remove("mail.user"); props.remove("mail.user.password"); Session session = Session.getInstance(props, auth); String htmlContent = emailBody; htmlContent = htmlContent.replaceFirst("TITLE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".title")); htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT", emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject")); htmlContent = htmlContent.replaceFirst("HEADER1", emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1")); htmlContent = htmlContent.replaceFirst("MESSAGE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".message")); htmlContent = htmlContent.replaceFirst("SALUTATION", salutation); htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); htmlContent = htmlContent.replaceFirst("REFERER", refID); htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'"); htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'"); String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - " + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n" + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"); textContent = textContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); textContent = textContent.replaceFirst("REFERER", refID); textContent = textContent.replaceFirst("SALUTATION", salutation); textContent = textContent.replaceAll("<br>", "\n"); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress()); msg.setSentDate(new Date()); msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject")); Multipart mp = new MimeMultipart("alternative"); // plaintext MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(textContent); mp.addBodyPart(textPart); // html MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); MimeBodyPart imagePart = new MimeBodyPart(); DataSource fds = null; try { fds = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart.setDataHandler(new DataHandler(fds)); imagePart.setHeader("Content-ID", "header-image"); mp.addBodyPart(imagePart); MimeBodyPart imagePart2 = new MimeBodyPart(); DataSource fds2 = null; try { fds2 = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.dash")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart2.setDataHandler(new DataHandler(fds2)); imagePart2.setHeader("Content-ID", "dash"); mp.addBodyPart(imagePart2); msg.setContent(mp); Transport.send(msg); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); return false; } return true; }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
/** * Sets the content for a message. Also attaches files to the message. * @throws MessagingException/*from w ww . j ava 2 s.c o m*/ */ protected void setContent(String content, List<Attachment> attachments, MimeMessage msg, String contentType, String charset, String multipartSubtype) throws MessagingException { ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>(); if (attachments != null && attachments.size() > 0) { // Add attachments to messages for (Attachment attachment : attachments) { // attach the file to the message embeddedAttachments.add(createAttachmentPart(attachment)); } } // if no direct attachments, keep the message simple and add the content as text. if (embeddedAttachments.size() == 0) { // if no contentType specified, go with text/plain if (contentType == null) msg.setText(content, charset); else msg.setContent(content, contentType); } // the multipart was constructed (ie. attachments available), use it as the message content else { // create a multipart container Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype) : new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); if (contentType == null) msgBodyPart.setText(content, charset); else msgBodyPart.setContent(content, contentType); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (MimeBodyPart attachPart : embeddedAttachments) { multipart.addBodyPart(attachPart); } // set the multipart container as the content of the message msg.setContent(multipart); } }