Example usage for org.apache.commons.mail Email addHeader

List of usage examples for org.apache.commons.mail Email addHeader

Introduction

In this page you can find the example usage for org.apache.commons.mail Email addHeader.

Prototype

public void addHeader(final String name, final String value) 

Source Link

Document

Adds a header ( name, value ) to the headers Map.

Usage

From source file:com.packtpub.e4.advanced.event.mailman.MailSender.java

@Override
public void handleEvent(Event event) {
    String topic = event.getTopic();
    if (topic.startsWith("smtp/")) {
        String importance = topic.substring("smtp/".length());
        String to = (String) event.getProperty("To");
        String from = (String) event.getProperty("From");
        String subject = (String) event.getProperty("Subject");
        String body = (String) event.getProperty("DATA");
        try {/*from w  w w. ja v  a 2s  .  c  o m*/
            Email email = new SimpleEmail();
            email.setDebug(false);
            email.setHostName(hostname);
            email.setSmtpPort(port);
            email.setFrom(from);
            email.addTo(to);
            email.setSubject(subject);
            email.setMsg(body);
            email.addHeader("Importance", importance);
            email.send();
            log(LogService.LOG_INFO, "Message sent successfully to " + to);
        } catch (EmailException e) {
            log(LogService.LOG_ERROR, "Error occurred" + e);
        }
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//  w  w w . ja va  2 s .  com
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint 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 saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, 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 = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        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) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            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.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*from  w  w w  . ja  v  a  2 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, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, 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 = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        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) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        String mid = getId();

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        } else {
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            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.saveSentMessage(mid, mime, user);

        Thread thread = new Thread(new SendMessageThread(email));
        thread.start();
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java

@Override
public void doDispatch(UMOEvent event) throws Exception {
    monitoringController.updateStatus(connector, connectorType, Event.BUSY);
    MessageObject mo = messageObjectController.getMessageObjectFromEvent(event);

    if (mo == null) {
        return;//from ww w. java 2 s  . c  o  m
    }

    try {
        Email email = null;

        if (connector.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(connector.getCharsetEncoding());

        email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo));

        try {
            email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        try {
            email.setSocketConnectionTimeout(
                    Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        if ("SSL".equalsIgnoreCase(connector.getEncryption())) {
            email.setSSL(true);
        } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) {
            email.setTLS(true);
        }

        if (connector.isAuthentication()) {
            email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo),
                    replacer.replaceValues(connector.getPassword(), mo));
        }

        /*
         * NOTE: There seems to be a bug when calling setTo with a List
         * (throws a java.lang.ArrayStoreException), so we are using addTo
         * instead.
         */

        for (String to : replaceValuesAndSplit(connector.getTo(), mo)) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : replaceValuesAndSplit(connector.cc(), mo)) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : connector.getHeaders().entrySet()) {
            email.addHeader(replacer.replaceValues(header.getKey(), mo),
                    replacer.replaceValues(header.getValue(), mo));
        }

        email.setFrom(replacer.replaceValues(connector.getFrom(), mo));
        email.setSubject(replacer.replaceValues(connector.getSubject(), mo));

        String body = replacer.replaceValues(connector.getBody(), mo);

        if (connector.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        /*
         * If the MIME type for the attachment is missing, we display a
         * warning and set the content anyway. If the MIME type is of type
         * "text" or "application/xml", then we add the content. If it is
         * anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : connector.getAttachments()) {
            String name = replacer.replaceValues(attachment.getName(), mo);
            String mimeType = replacer.replaceValues(attachment.getMimeType(), mo);
            String content = replacer.replaceValues(attachment.getContent(), mo);

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = content.getBytes();
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = content.getBytes();
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = Base64.decodeBase64(content);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        String response = email.send();
        messageObjectController.setSuccess(mo, response, null);
    } catch (EmailException e) {
        alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402,
                "Error sending email message.", e);
        messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null);
        connector.handleException(new Exception(e));
    } finally {
        monitoringController.updateStatus(connector, connectorType, Event.DONE);
    }
}

From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java

/**
 * Email/*from  w ww  . j a v a  2 s. com*/
 * 
 * @param mail
 * @return
 * @throws Exception
 */
protected Email getEmail(MsunMail mail) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("send mail use smth : " + hostName);
    }
    // set env for logger
    mail.getEnvironment().setHostName(hostName);
    mail.getEnvironment().setUser(user);
    mail.getEnvironment().setPassword(password);

    Email email = null;

    if (!StringUtils.isEmpty(mail.getHtmlMessage())) {
        email = makeHtmlEmail(mail, mail.getCharset());
    } else {
        if ((mail.getAttachment() == null || mail.getAttachment().length == 0)
                && mail.getAttachments().isEmpty()) {
            email = makeSimpleEmail(mail, mail.getCharset());
        } else {
            email = makeSimpleEmailWithAttachment(mail, mail.getCharset());
        }
    }

    if (auth) {
        // email.setAuthenticator(new MyAuthenticator(user, password));
        email.setAuthentication(user, password);
    }
    email.setHostName(hostName);

    if (mail.getTo() == null) {
        mail.setTo(defaultTo.split(";"));
    }

    if (StringUtils.isEmpty(mail.getFrom())) {
        mail.setFrom(defaultFrom);
    }

    email.setFrom(mail.getFrom(), mail.getFromName());

    List<String> unqualifiedReceiver = mail.getUnqualifiedReceiver();
    String[] mailTo = mail.getTo();
    String[] mailCc = mail.getCc();
    String[] mailBcc = mail.getBcc();
    if (unqualifiedReceiver != null && unqualifiedReceiver.size() > 0) {
        if (mailTo != null && mailTo.length > 0) {
            mailTo = filterReceiver(mailTo, unqualifiedReceiver);
        }
        if (mailCc != null && mailCc.length > 0) {
            mailCc = filterReceiver(mailCc, unqualifiedReceiver);
        }
        if (mailBcc != null && mailBcc.length > 0) {
            mailBcc = filterReceiver(mailBcc, unqualifiedReceiver);
        }
    }

    if (mailTo == null && mailCc == null && mailBcc == null) {
        throw new MessageSerivceException("?????");
    }

    int count = 0;

    if (mailTo != null) {
        count += mailTo.length;
        for (String to : mailTo) {
            email.addTo(to);
        }
    }

    if (mailCc != null) {
        count += mailCc.length;
        for (String cc : mailCc) {
            email.addCc(cc);
        }
    }
    if (mailBcc != null) {
        count += mailBcc.length;
        for (String bcc : mailBcc) {
            email.addBcc(bcc);
        }
    }

    if (count < 1) {
        throw new MessageSerivceException("?????");
    }

    if (!StringUtils.isEmpty(mail.getReplyTo())) {
        email.addReplyTo(mail.getReplyTo());
    }

    if (mail.getHeaders() != null) {
        for (Iterator<String> iter = mail.getHeaders().keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            email.addHeader(key, (String) mail.getHeaders().get(key));
        }
    }

    email.setSubject(mail.getSubject());

    // 
    if (email instanceof MultiPartEmail) {
        MultiPartEmail multiEmail = (MultiPartEmail) email;

        if (mail.getAttachments().isEmpty()) {
            File[] fs = mail.getAttachment();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(fs[i].getAbsolutePath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setName(MimeUtility.encodeText(fs[i].getName()));// ???
                    multiEmail.attach(attachment);
                }
            }
        } else {
            for (MsunMailAttachment attachment : mail.getAttachments()) {
                DataSource ds = new ByteArrayDataSource(attachment.getData(), null);
                multiEmail.attach(ds, MimeUtility.encodeText(attachment.getName()), null);
            }
        }
    }
    return email;
}

From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties;
    String responseData = null;//from   ww  w  .  j av  a2 s  .  com
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;

    String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo()
            + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":"
            + smtpDispatcherProperties.getSmtpPort();
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING, info));

    try {
        Email email = null;

        if (smtpDispatcherProperties.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charsetEncoding);

        email.setHostName(smtpDispatcherProperties.getSmtpHost());

        try {
            email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort()));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        try {
            int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout());
            email.setSocketTimeout(timeout);
            email.setSocketConnectionTimeout(timeout);
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        // This has to be set before the authenticator because a session shouldn't be created yet
        configuration.configureEncryption(connectorProperties, email);

        if (smtpDispatcherProperties.isAuthentication()) {
            email.setAuthentication(smtpDispatcherProperties.getUsername(),
                    smtpDispatcherProperties.getPassword());
        }

        Properties mailProperties = email.getMailSession().getProperties();
        // These have to be set after the authenticator, so that a new mail session isn't created
        configuration.configureMailProperties(mailProperties);

        if (smtpDispatcherProperties.isOverrideLocalBinding()) {
            mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress());
            mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort());
        }
        /*
         * NOTE: There seems to be a bug when calling setTo with a List (throws a
         * java.lang.ArrayStoreException), so we are using addTo instead.
         */

        for (String to : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) {
            email.addHeader(header.getKey(), header.getValue());
        }

        email.setFrom(smtpDispatcherProperties.getFrom());
        email.setSubject(smtpDispatcherProperties.getSubject());

        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();

        String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(),
                connectorMessage);

        if (StringUtils.isNotEmpty(body)) {
            if (smtpDispatcherProperties.isHtml()) {
                ((HtmlEmail) email).setHtmlMsg(body);
            } else {
                email.setMsg(body);
            }
        }

        /*
         * If the MIME type for the attachment is missing, we display a warning and set the
         * content anyway. If the MIME type is of type "text" or "application/xml", then we add
         * the content. If it is anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : smtpDispatcherProperties.getAttachments()) {
            String name = attachment.getName();
            String mimeType = attachment.getMimeType();
            String content = attachment.getContent();

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        responseData = email.send();
        responseStatus = Status.SENT;
        responseStatusMessage = "Email sent successfully.";
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error sending email message", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error sending email message", e);

        // TODO: Exception handling
        //            connector.handleException(new Exception(e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError);
}

From source file:org.xerela.server.birt.ReportJob.java

private void setupEmail(JobExecutionContext executionContext, String emailTo, String emailCc, Email email)
        throws AddressException, EmailException {
    InternetAddress[] toAddrs = InternetAddress.parse(emailTo);
    email.setTo(Arrays.asList(toAddrs));

    if (emailCc != null && emailCc.trim().length() > 0) {
        InternetAddress[] ccAddrs = InternetAddress.parse(emailCc);
        email.setCc(Arrays.asList(ccAddrs));
    }//from www.j a v a  2  s  .  co  m

    email.setCharset("utf-8"); //$NON-NLS-1$
    email.setHostName(System.getProperty(MAIL_HOST_PROP, "mail")); //$NON-NLS-1$
    String authUser = System.getProperty(MAIL_AUTH_USER_PROP);
    if (authUser != null) {
        email.setAuthentication(authUser, System.getProperty(MAIL_AUTH_PASSWORD_PROP));
    }
    email.setFrom(System.getProperty(MAIL_FROM_PROP), System.getProperty(MAIL_FROM_NAME_PROP));
    email.setSubject(
            Messages.bind(Messages.ReportJob_emailSubject, executionContext.getJobDetail().getFullName()));
    email.addHeader("X-Mailer", "Xerela Mailer"); //$NON-NLS-1$ //$NON-NLS-2$
    email.setDebug(Boolean.getBoolean("org.xerela.mail.debug")); //$NON-NLS-1$
}