List of usage examples for javax.mail BodyPart setContent
public void setContent(Object obj, String type) throws MessagingException;
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"); }//w ww. j av a 2 s .c o 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.eurekastreams.server.service.actions.strategies.EmailerFactory.java
/** * @param message/*from ww w . j a va2s . c o m*/ * Email message being built. * @param htmlBody * Rich HTML body of the Email. * @throws MessagingException * Thrown if there are problems creating the message. */ public void setHtmlBody(final MimeMessage message, final String htmlBody) throws MessagingException { BodyPart htmlBp = new MimeBodyPart(); htmlBp.setContent(htmlBody, "text/html"); htmlBp.setHeader("MIME-VERSION", "1.0"); htmlBp.setHeader("Content-Type", "text/html; charset=ISO-8859-1"); getMultipart(message).addBodyPart(htmlBp); }
From source file:org.grouter.common.mail.MailHandler.java
/** * Creates a multipart email with html and plain text email body to fallback to if * email client do not handle html base emails. * * @param mimeMessage/*from ww w.ja v a 2 s .c o m*/ * @param dto * @throws MessagingException */ private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException { if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) { mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE); // Create your text message part BodyPart plainBodyPart = new MimeBodyPart(); plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainBodyPart); StringBuilder sb = new StringBuilder(); sb.append(PRE_HTML_HEADER); sb.append(dto.getSubject()).append("\n"); sb.append(POST_HTML_HEADER); sb.append(dto.getHtmlTextBody()); sb.append(END_HTML); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML); // Add html part to multi part multipart.addBodyPart(htmlBodyPart); mimeMessage.setContent(multipart); } else { mimeMessage.setSubject(dto.getSubject()); mimeMessage.setText(dto.getPlainTextBody()); mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); } }
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 .ja v a 2s . 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; }
From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java
protected void fillContent(MailTemplate template, Message email, WorkItem workItem, JCRSessionWrapper session) throws Exception { String text = template.getText(); String html = template.getHtml(); List<AttachmentTemplate> attachmentTemplates = template.getAttachmentTemplates(); if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p);/*from w w w . j a va 2s. c o m*/ // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(workItem, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(workItem, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(template, workItem, multipart, session); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(workItem, text, session); email.setText(text); } }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
protected void fillContent(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String text = getTemplate().getText(); String html = getTemplate().getHtml(); List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates(); try {// www.j av a2 s. c o m if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p); // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(execution, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(execution, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(execution, multipart); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(execution, text, session); email.setText(text); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }
From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java
private String buildEnrichedMimeMessage(String enrichedSOAPMessage) throws MessagingException, IOException { for (int i = 0; i < mimeMessage.getCount(); i++) { BodyPart part = mimeMessage.getBodyPart(i); if (part.getContentType().contains("application/soap+xml")) { Enumeration copyOfHeaders = createCopyOfHeaders(part); part.setContent(enrichedSOAPMessage, part.getContentType()); copyHeadersToPart(copyOfHeaders, part); break; }/*from w w w. jav a2s . c om*/ } ByteArrayOutputStream out = new ByteArrayOutputStream(); mimeMessage.writeTo(out); mimeMessage = null; return out.toString(); }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }// w ww. jav a 2 s. co m // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }