Example usage for javax.mail.internet MimeMessage setHeader

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

Introduction

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

Prototype

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

Source Link

Document

Set the value for this header_name.

Usage

From source file:org.craftercms.social.services.system.EmailService.java

public void sendEmail(final Profile toSend, final StringWriter writer, final String subject,
        final String contextId) throws SocialException {
    Map<String, Object> emailSettings = getEmailSettings(contextId);
    JavaMailSender sender = getSender(contextId);
    MimeMessage message = sender.createMimeMessage();
    String realSubject = subject;
    if (StringUtils.isBlank(realSubject)) {
        realSubject = generateSubjectString(emailSettings.get("subject").toString());
    }/*from www .  j  a  v  a  2  s  .co m*/
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(toSend.getEmail());
        helper.setReplyTo(emailSettings.get("replyTo").toString());
        helper.setFrom(emailSettings.get("from").toString());
        helper.setSubject(realSubject);

        helper.setPriority(NumberUtils.toInt(emailSettings.get("priority").toString(), 4));
        helper.setText(writer.toString(), true);
        message.setHeader("Message-ID", String.format("[%s]-%s-%s-%s", RandomStringUtils.randomAlphanumeric(5),
                contextId, realSubject, toSend.getId()));
        sender.send(message);
    } catch (MessagingException e) {
        throw new SocialException("Unable to send Email to " + toSend.getEmail(), e);
    }
}

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   w  w  w .ja v  a  2s. 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;
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final void send(String to, String cc, String bcc, String subject, String memo, boolean html)
        throws Exception {
    MimeMessage mimeMessage = new MimeMessage(smtpSession);

    // Add 'to' fields
    StringTokenizer st = new StringTokenizer(to, ", ");
    while (st.hasMoreTokens()) {
        mimeMessage.addRecipients(Message.RecipientType.TO, st.nextToken());
    }//w w w . j  a  v a2  s  . c  o m

    // Add 'cc' fields
    if (cc != null && cc.length() != 0) {
        st = new StringTokenizer(cc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.CC, st.nextToken());
        }
    }

    // Add 'bcc' fields
    if (bcc != null && bcc.length() != 0) {
        st = new StringTokenizer(bcc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.BCC, st.nextToken());
        }
    }

    // Set message
    if (html) {
        mimeMessage.setHeader("Content-Type", "text/html");
        mimeMessage.setContent(memo.trim(), "text/html; charset=UTF-8");
    } else {
        mimeMessage.setHeader("Content-Type", "text/plain");
        mimeMessage.setContent(memo.trim(), "text/plain; charset=UTF-8");
    }

    // Set 'from', 'subject' and date fields
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.setSubject(subject.trim(), "UTF-8");
    mimeMessage.setSentDate(new Date());
    Transport.send(mimeMessage);
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server// ww w.j  a v  a 2s .c  o m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*  w ww.java  2  s  .c  om*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

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);/*from   w ww .  j  av a 2 s  .  c o 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:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject,
        String htmlContent, String inReplyTo, String references) throws SendFailedException {

    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;/*from w ww.  ja  va 2 s  .  c om*/
    }
    // get the mail session
    Session session = getMailSession();

    // Define message
    MimeMessage messageMim = new MimeMessage(session);

    try {
        messageMim.setFrom(new InternetAddress(smtpSender));

        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }

        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));

        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }

        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }

        messageMim.setSubject(subject, charset);

        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");

        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");

        // Include an HTML message with images.
        // BodyParts: the HTML file and an image

        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(
                new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);

        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);

        messageMim.setContent(mp);

        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());

        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);

        Transport tr = session.getTransport("smtp");

        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient,
                e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.//from   w w w. j  a v  a2  s. com
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}

From source file:org.mule.transport.email.transformers.StringToEmailMessage.java

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
            connector.getReplyToAddresses());
    String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY,
            connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
        headers.putAll(customHeaders);//  ww w.  j  a v a2s . c om
    }

    Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
        //TODO Whats going on here?
        //                final MuleContext mc = context.getMuleContext();
        //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
        //                {
        //                    String propertyKey = (String) iterator.next();
        //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
        //                }
        headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() {
            public Object match(String token) {
                return muleContext.getRegistry().lookupObject(token);
            }
        }, otherHeaders));

    }

    if (logger.isDebugEnabled()) {
        StringBuffer buf = new StringBuffer();
        buf.append("Constructing email using:\n");
        buf.append("To: ").append(to);
        buf.append(", From: ").append(from);
        buf.append(", CC: ").append(cc);
        buf.append(", BCC: ").append(bcc);
        buf.append(", Subject: ").append(subject);
        buf.append(", ReplyTo: ").append(replyTo);
        buf.append(", Content type: ").append(contentType);
        buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
        buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
        logger.debug(buf.toString());
    }

    try {
        MimeMessage email = new MimeMessage(
                ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());

        email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

        // sent date
        email.setSentDate(Calendar.getInstance().getTime());

        if (StringUtils.isNotBlank(from)) {
            email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
        }

        if (StringUtils.isNotBlank(cc)) {
            email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
        }

        if (StringUtils.isNotBlank(bcc)) {
            email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
        }

        if (StringUtils.isNotBlank(replyTo)) {
            email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
        }

        email.setSubject(subject, outputEncoding);

        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            email.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }

        setContent(message.getPayload(), email, contentType, message);

        return email;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*w  ww  .ja va 2s . com*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}