Example usage for javax.mail.internet MimeMessage addHeader

List of usage examples for javax.mail.internet MimeMessage addHeader

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage addHeader.

Prototype

@Override
public void addHeader(String name, String value) throws MessagingException 

Source Link

Document

Add this value to the existing values for this header_name.

Usage

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!/*  w ww .  j a  v  a 2s.  co  m*/
 *
 * @param id DOCUMENT ME!
 * @param mime DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private String getParentId(String id, MimeMessage mime) {
    String references = null;

    try {
        if (references == null) {
            String[] aux = mime.getHeader(RFC2822Headers.REFERENCES);

            //Cal controlar que portem un array
            if ((aux != null) && (aux.length > 0)) {
                if (aux[0] != null) {
                    String[] ref = aux[0].split("\\s+");

                    if ((ref != null) && (ref.length > 1)) {
                        references = ref[0];
                    }
                }

                if (references == null) {
                    references = aux[0];
                }
            }
        }

        if (references == null) {
            String[] aux = mime.getHeader(RFC2822Headers.IN_REPLY_TO);

            //Cal veure que portem un array
            if ((aux != null) && (aux.length > 0)) {
                references = aux[0];
            }
        }

        if (references == null) {
            references = mime.getMessageID();

            mime.addHeader(RFC2822Headers.IN_REPLY_TO, references);
            mime.addHeader(RFC2822Headers.REFERENCES, references);
        }
    } catch (MessagingException e) {
        references = null;
    }

    return references;
}

From source file:org.apache.camel.component.mail.MailBinding.java

/**
 * Appends the Mail headers from the Camel {@link MailMessage}
 *//*from   ww w .  j a v a 2s  . c o m*/
protected void appendHeadersFromCamelMessage(MimeMessage mimeMessage, MailConfiguration configuration,
        Exchange exchange) throws MessagingException {

    for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
        String headerName = entry.getKey();
        Object headerValue = entry.getValue();
        if (headerValue != null) {
            if (headerFilterStrategy != null
                    && !headerFilterStrategy.applyFilterToCamelHeaders(headerName, headerValue, exchange)) {
                if (headerName.equalsIgnoreCase("subject")) {
                    mimeMessage.setSubject(asString(exchange, headerValue),
                            IOConverter.getCharsetName(exchange, false));
                    continue;
                }
                if (isRecipientHeader(headerName)) {
                    // skip any recipients as they are handled specially
                    continue;
                }

                // alternative body should also be skipped
                if (headerName.equalsIgnoreCase(configuration.getAlternativeBodyHeader())) {
                    // skip alternative body
                    continue;
                }

                // Mail messages can repeat the same header...
                if (ObjectConverter.isCollection(headerValue)) {
                    Iterator iter = ObjectHelper.createIterator(headerValue);
                    while (iter.hasNext()) {
                        Object value = iter.next();
                        mimeMessage.addHeader(headerName, asString(exchange, value));
                    }
                } else {
                    mimeMessage.setHeader(headerName, asString(exchange, headerValue));
                }
            }
        }
    }
}

From source file:org.jnap.core.email.Email.java

public void prepare(MimeMessage mimeMessage) throws Exception {
    final EmailAccountInfo acc = getAccountInfo();
    boolean multipart = StringUtils.isNotBlank(getHtmlText())
            || (getInlineResources() != null && getInlineResources().size() > 0)
            || (getAttachments() != null && getAttachments().size() > 0);

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
    if (acc.getFromName() != null) {
        helper.setFrom(acc.getFromEmailAddress(), acc.getFromName());
    } else {//w ww .ja  v  a2 s . com
        this.setFrom(acc.getFromEmailAddress());
    }
    helper.setTo(getTo());
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    mimeMessage.setSubject(getMessage(getSubject()), this.encoding);

    // sender info
    if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
        helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName()));
    } else {
        helper.setFrom(acc.getFromEmailAddress());
    }
    if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) {
        if (StringUtils.isNotBlank(acc.getReplyToName())) {
            helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName());
        } else {
            helper.setReplyTo(acc.getReplyToEmailAddress());
        }
    }

    final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText());
    final boolean hasText = StringUtils.isNotBlank(getText());
    if (hasHtmlText && hasText) {
        helper.setText(getText(), getHtmlText());
    } else if (hasHtmlText || hasText) {
        helper.setText(hasHtmlText ? getHtmlText() : getText());
    }

    // set headers
    final Map<String, String> mailHeaders = this.getHeaders();
    for (String header : mailHeaders.keySet()) {
        mimeMessage.addHeader(header, mailHeaders.get(header));
    }

    // add inline resources
    final Map<String, Resource> inlineRes = this.getInlineResources();
    if (inlineRes != null) {
        for (String cid : inlineRes.keySet()) {
            helper.addInline(cid, inlineRes.get(cid));
        }
    }
    // add attachments
    final Map<String, Resource> attachments = this.getAttachments();
    if (attachments != null) {
        for (String attachmentName : attachments.keySet()) {
            helper.addAttachment(attachmentName, attachments.get(attachmentName));
        }
    }
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Get item content./*from www  .  jav a2s  .  c om*/
 *
 * @param itemId EWS item id
 * @return item content as byte array
 * @throws IOException on error
 */
protected byte[] getContent(ItemId itemId) throws IOException {
    GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
    byte[] mimeContent = null;
    try {
        executeMethod(getItemMethod);
        mimeContent = getItemMethod.getMimeContent();
    } catch (EWSException e) {
        LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage());
    }
    if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        throw new HttpNotFoundException("Item " + itemId + " not found");
    }
    if (mimeContent == null) {
        LOGGER.warn("MimeContent not available, trying to rebuild from properties");
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
            getItemMethod.addAdditionalProperty(Field.get("contentclass"));
            getItemMethod.addAdditionalProperty(Field.get("message-id"));
            getItemMethod.addAdditionalProperty(Field.get("from"));
            getItemMethod.addAdditionalProperty(Field.get("to"));
            getItemMethod.addAdditionalProperty(Field.get("cc"));
            getItemMethod.addAdditionalProperty(Field.get("subject"));
            getItemMethod.addAdditionalProperty(Field.get("date"));
            getItemMethod.addAdditionalProperty(Field.get("body"));
            executeMethod(getItemMethod);
            EWSMethod.Item item = getItemMethod.getResponseItem();

            MimeMessage mimeMessage = new MimeMessage((Session) null);
            mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName()));
            mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName())));
            mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName()));
            mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName()));
            mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName()));
            mimeMessage.setSubject(item.get(Field.get("subject").getResponseName()));
            String propertyValue = item.get(Field.get("body").getResponseName());
            if (propertyValue == null) {
                propertyValue = "";
            }
            mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");

            mimeMessage.writeTo(baos);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
            mimeContent = baos.toByteArray();

        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        if (mimeContent == null) {
            throw new IOException("GetItem returned null MimeContent");
        }
    }
    return mimeContent;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail.// w w  w.j a va 2s . 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;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail.//from w w w.  j av  a2s  .  com
 * 
 * @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 && Config.SEND_MAIL_FROM_USER) {
        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;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object// w w  w.  jav  a2  s.  c  om
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // 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(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(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(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc//from w ww  . ja v a  2 s  . c o  m
 */
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream contentInputStream;
    try {
        try {
            try {
                contentInputStream = getContentInputStream(message.messageUrl);
            } catch (UnknownHostException e) {
                // failover for misconfigured Exchange server, replace host name in url
                restoreHostName = true;
                contentInputStream = getContentInputStream(message.messageUrl);
            }
        } catch (HttpNotFoundException e) {
            LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
            contentInputStream = getContentInputStream(message.permanentUrl);
        }

        try {
            IOUtil.write(contentInputStream, baos);
        } finally {
            contentInputStream.close();
        }

    } catch (LoginTimeoutException e) {
        // throw error on expired session
        LOGGER.warn(e.getMessage());
        throw e;
    } catch (IOException e) {
        LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl
                + ", trying to rebuild from properties");

        try {
            DavPropertyNameSet messageProperties = new DavPropertyNameSet();
            messageProperties.add(Field.getPropertyName("contentclass"));
            messageProperties.add(Field.getPropertyName("message-id"));
            messageProperties.add(Field.getPropertyName("from"));
            messageProperties.add(Field.getPropertyName("to"));
            messageProperties.add(Field.getPropertyName("cc"));
            messageProperties.add(Field.getPropertyName("subject"));
            messageProperties.add(Field.getPropertyName("date"));
            messageProperties.add(Field.getPropertyName("htmldescription"));
            messageProperties.add(Field.getPropertyName("body"));
            PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl),
                    messageProperties, 0);
            DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
            MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
            if (responses.getResponses().length > 0) {
                MimeMessage mimeMessage = new MimeMessage((Session) null);

                DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
                String propertyValue = getPropertyIfExists(properties, "contentclass");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Content-class", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "date");
                if (propertyValue != null) {
                    mimeMessage.setSentDate(parseDateFromExchange(propertyValue));
                }
                propertyValue = getPropertyIfExists(properties, "from");
                if (propertyValue != null) {
                    mimeMessage.addHeader("From", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "to");
                if (propertyValue != null) {
                    mimeMessage.addHeader("To", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "cc");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Cc", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "subject");
                if (propertyValue != null) {
                    mimeMessage.setSubject(propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "htmldescription");
                if (propertyValue != null) {
                    mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
                } else {
                    propertyValue = getPropertyIfExists(properties, "body");
                    if (propertyValue != null) {
                        mimeMessage.setText(propertyValue);
                    }
                }
                mimeMessage.writeTo(baos);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (DavException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        // other exception
        if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
            LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: "
                    + message.permanentUrl);
            try {
                message.delete();
            } catch (IOException ioe) {
                LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
            }
            throw e;
        }
    }

    return baos.toByteArray();
}

From source file:davmail.exchange.ExchangeSession.java

protected void convertResentHeader(MimeMessage mimeMessage, String headerName) throws MessagingException {
    String[] resentHeader = mimeMessage.getHeader("Resent-" + headerName);
    if (resentHeader != null) {
        mimeMessage.removeHeader("Resent-" + headerName);
        mimeMessage.removeHeader(headerName);
        for (String value : resentHeader) {
            mimeMessage.addHeader(headerName, value);
        }//  w  w w .  jav a2  s.c o m
    }
}

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 www.j a va 2  s .c  o  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;
}