List of usage examples for org.apache.commons.mail MultiPartEmail addHeader
public void addHeader(final String name, final String value)
From source file:com.pushinginertia.commons.net.email.EmailUtils.java
/** * Populates a newly instantiated {@link MultiPartEmail} with the given arguments. * @param email email instance to populate * @param smtpHost SMTP host that the message will be sent to * @param msg container object for the email's headers and contents * @throws IllegalArgumentException if the inputs are not valid * @throws EmailException if a problem occurs constructing the email *//*from w w w .j av a 2 s. com*/ public static void populateMultiPartEmail(final MultiPartEmail email, final String smtpHost, final EmailMessage msg) throws IllegalArgumentException, EmailException { ValidateAs.notNull(email, "email"); ValidateAs.notNull(smtpHost, "smtpHost"); ValidateAs.notNull(msg, "msg"); email.setHostName(smtpHost); email.setCharset(UTF_8); email.setFrom(msg.getSender().getEmail(), msg.getSender().getName(), UTF_8); email.addTo(msg.getRecipient().getEmail(), msg.getRecipient().getName(), UTF_8); final NameEmail replyTo = msg.getReplyTo(); if (replyTo != null) { email.addReplyTo(replyTo.getEmail(), replyTo.getName(), UTF_8); } final String bounceEmailAddress = msg.getBounceEmailAddress(); if (bounceEmailAddress != null) { email.setBounceAddress(bounceEmailAddress); } email.setSubject(msg.getSubject()); final String languageId = msg.getRecipient().getLanguage(); if (languageId != null) { email.addHeader("Language", languageId); email.addHeader("Content-Language", languageId); } // add optional headers final EmailMessageHeaders headers = msg.getHeaders(); if (headers != null) { for (final Map.Entry<String, String> header : headers.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } } // generate email body try { final MimeMultipart mm = new MimeMultipart("alternative; charset=UTF-8"); final MimeBodyPart text = new MimeBodyPart(); text.setContent(msg.getTextContent(), "text/plain; charset=UTF-8"); mm.addBodyPart(text); final MimeBodyPart html = new MimeBodyPart(); html.setContent(msg.getHtmlContent(), "text/html; charset=UTF-8"); mm.addBodyPart(html); email.setContent(mm); } catch (MessagingException e) { throw new EmailException(e); } }
From source file:com.duroty.application.files.manager.StoreManager.java
/** * DOCUMENT ME!// www.j a va2 s. c o m * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); //email.setMsg(body); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
From source file:org.apache.nifi.processors.email.ConsumeEWS.java
public MimeMessage parseMessage(EmailMessage item) throws Exception { EmailMessage ewsMessage = item;/*ww w . j a va2 s. c o m*/ final String bodyText = ewsMessage.getBody().toString(); MultiPartEmail mm; if (ewsMessage.getBody().getBodyType() == BodyType.HTML) { mm = new HtmlEmail().setHtmlMsg(bodyText); } else { mm = new MultiPartEmail(); mm.setMsg(bodyText); } mm.setHostName("NiFi-EWS"); //from mm.setFrom(ewsMessage.getFrom().getAddress()); //to recipients ewsMessage.getToRecipients().forEach(x -> { try { mm.addTo(x.getAddress()); } catch (EmailException e) { throw new ProcessException("Failed to add TO recipient.", e); } }); //cc recipients ewsMessage.getCcRecipients().forEach(x -> { try { mm.addCc(x.getAddress()); } catch (EmailException e) { throw new ProcessException("Failed to add CC recipient.", e); } }); //subject mm.setSubject(ewsMessage.getSubject()); //sent date mm.setSentDate(ewsMessage.getDateTimeSent()); //add message headers ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue())); //Any attachments if (ewsMessage.getHasAttachments()) { ewsMessage.getAttachments().forEach(x -> { try { FileAttachment file = (FileAttachment) x; file.load(); ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType()); mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }); } mm.buildMimeMessage(); return mm.getMimeMessage(); }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
protected MultiPartEmail constructMessage(Content contentNode, List<String> recipients, javax.jcr.Session session, org.sakaiproject.nakamura.api.lite.Session sparseSession) throws EmailDeliveryException, StorageClientException, AccessDeniedException, PathNotFoundException, RepositoryException, EmailException { MultiPartEmail email = new MultiPartEmail(); Set<String> toRecipients = new HashSet<String>(); toRecipients = setRecipients(recipients, sparseSession); String to = null;// ww w . ja v a2s .c o m try { // set from: to the reply as address email.setFrom(replyAsAddress, replyAsName); if (toRecipients.size() == 1) { // set to: to the rcpt if sending to just one person to = convertToEmail(toRecipients.iterator().next(), sparseSession); email.setTo(Lists.newArrayList(new InternetAddress(to))); } else { // set to: to 'undisclosed recipients' when sending to a group of recipients // this mirrors what shows up in RFC's and most major MTAs // http://www.postfix.org/postconf.5.html#undisclosed_recipients_header email.addHeader("To", "undisclosed-recipients:;"); } } catch (EmailException e) { LOGGER.error("Cannot send email. From: address as configured is not valid: {}", replyAsAddress); } catch (AddressException e) { LOGGER.error("Cannot send email. To: address is not valid: {}", to); } // if we're dealing with a group of recipients, add them to bcc: to hide email // addresses from the other recipients if (toRecipients.size() > 1) { for (String r : toRecipients) { try { // we don't need to copy the sender on the message if (r.equals(contentNode.getProperty(MessageConstants.PROP_SAKAI_FROM))) { continue; } email.addBcc(convertToEmail(r, sparseSession)); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid To Address [" + r + "], message is being dropped :" + e.getMessage(), e); } } } if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_BODY)) { String messageBody = String.valueOf(contentNode.getProperty(MessageConstants.PROP_SAKAI_BODY)); // if this message has a template, use it LOGGER.debug( "Checking for sakai:templatePath and sakai:templateParams properties on the outgoing message's node."); if (contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PATH) && contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PARAMS)) { Map<String, String> parameters = getTemplateProperties( (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PARAMS)); String templatePath = (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PATH); LOGGER.debug("Got the path '{0}' to the template for this outgoing message.", templatePath); Node templateNode = session.getNode(templatePath); if (templateNode.hasProperty("sakai:template")) { String template = templateNode.getProperty("sakai:template").getString(); LOGGER.debug("Pulled the template body from the template node: {0}", template); messageBody = templateService.evaluateTemplate(parameters, template); LOGGER.debug("Performed parameter substitution in the template: {0}", messageBody); } } else { LOGGER.debug( "Message node '{0}' does not have sakai:templatePath and sakai:templateParams properties", contentNode.getPath()); } try { email.setMsg(messageBody); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Message Body, message is being dropped :" + e.getMessage(), e); } } if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_SUBJECT)) { email.setSubject((String) contentNode.getProperty(MessageConstants.PROP_SAKAI_SUBJECT)); } ContentManager contentManager = sparseSession.getContentManager(); for (String streamId : contentNode.listStreams()) { String description = null; if (contentNode.hasProperty( StorageClientUtils.getAltField(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId))) { description = (String) contentNode.getProperty(StorageClientUtils .getAltField(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId)); } LiteEmailDataSource ds = new LiteEmailDataSource(contentManager, contentNode, streamId); try { email.attach(ds, streamId, description); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Attachment [" + streamId + "] message is being dropped :" + e.getMessage(), e); } } return email; }