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

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

Introduction

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

Prototype

public Email setTo(final Collection<InternetAddress> aCollection) throws EmailException 

Source Link

Document

Set a list of "TO" addresses.

Usage

From source file:de.hybris.basecommerce.SimpleSmtpServerUtilsTest.java

@Test
public void testSendSuccess() throws EmailException, AddressException {
    final String origMailPortNumber = Config.getParameter(Config.Params.MAIL_SMTP_PORT);
    final String origMailHost = Config.getParameter(Config.Params.MAIL_SMTP_SERVER);

    SimpleSmtpServer server = null;/*from   ww w .ja  v a2  s. com*/
    try {
        server = SimpleSmtpServerUtils.startServer(TEST_START_PORT);
        Assert.assertFalse(server.isStopped());
        Assert.assertTrue(server.getPort() > 0);

        Config.setParameter(Config.Params.MAIL_SMTP_SERVER, "localhost");
        Config.setParameter(Config.Params.MAIL_SMTP_PORT, String.valueOf(server.getPort()));

        final Email email = MailUtils.getPreConfiguredEmail();

        email.setFrom("foo.bar@hybris.com");
        email.setTo(Arrays.asList(InternetAddress.parse("foo.bar@hybris.com")));
        email.setSubject("TEST TEST TEST");
        email.setContent("FOO", Email.TEXT_PLAIN);

        email.send();
    } finally {
        Config.setParameter(Config.Params.MAIL_SMTP_SERVER, origMailHost);
        Config.setParameter(Config.Params.MAIL_SMTP_PORT, origMailPortNumber);

        if (server != null) {
            server.stop();
        }
    }
}

From source file:com.alkacon.opencms.newsletter.CmsNewsletterMail.java

/**
 * Sends the newsletter mails to the recipients.<p>
 *///  w  ww. j a v  a2s  . c  o m
public void sendMail() {

    Iterator<InternetAddress> i = getRecipients().iterator();
    while (i.hasNext()) {
        InternetAddress to = i.next();
        List<InternetAddress> toList = new ArrayList<InternetAddress>(1);
        toList.add(to);
        try {
            Email mail = getMailData().getEmail();
            mail.setTo(toList);
            mail.send();
        } catch (Exception e) {
            // log failed mail send process
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_SEND_FAILED_2,
                        to.getAddress(), getNewsletterName()));
            }
            // store message for error report mail
            getMailErrors()
                    .add(Messages.get().getBundle().key(Messages.MAIL_ERROR_EMAIL_ADDRESS_1, to.getAddress()));
        }
    }
}

From source file:com.alkacon.opencms.v8.newsletter.CmsNewsletterMail.java

/**
 * Sends the newsletter mails to the recipients.<p>
 *///from   www  .j a  v a 2  s  . com
public void sendMail() {

    Iterator<InternetAddress> i = getRecipients().iterator();
    int errLogCount = 0;
    while (i.hasNext()) {
        InternetAddress to = i.next();
        List<InternetAddress> toList = new ArrayList<InternetAddress>(1);
        toList.add(to);
        try {
            Email mail = getMailData().getEmail();
            mail.setTo(toList);
            mail.send();
        } catch (Exception e) {
            // log failed mail send process
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_SEND_FAILED_2,
                        to.getAddress(), getNewsletterName()));
            }
            if (LOG.isDebugEnabled() && (errLogCount < 10)) {
                LOG.debug(e);
                errLogCount++;
            }
            // store message for error report mail
            String errMsg = Messages.get().getBundle().key(Messages.MAIL_ERROR_EMAIL_ADDRESS_1,
                    to.getAddress());
            if (errLogCount == 10) {
                errMsg += "\nStack:\n" + errMsg + "\n";
            }
            getMailErrors().add(errMsg);
        }
    }
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImpl.java

@Override
public List<InternetAddress> sendEmail(final String templatePath, final Map<String, String> emailParams,
        final InternetAddress... recipients) {

    List<InternetAddress> failureList = new ArrayList<InternetAddress>();

    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }/*from  w w w . ja  v a 2s. c  o  m*/

    final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
    final Class<? extends Email> mailType = this.getMailType(templatePath);
    final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType);

    for (final InternetAddress address : recipients) {
        try {
            // Get a new email per recipient to avoid duplicate attachments
            final Email email = getEmail(mailTemplate, mailType, emailParams);
            email.setTo(Collections.singleton(address));
            messageGateway.send(email);
        } catch (Exception e) {
            failureList.add(address);
            log.error("Error sending email to [ " + address + " ]", e);
        }
    }

    return failureList;
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImpl.java

@Override
public List<InternetAddress> sendEmail(String templatePath, Map<String, String> emailParams,
        Map<String, DataSource> attachments, InternetAddress... recipients) {

    List<InternetAddress> failureList = new ArrayList<InternetAddress>();

    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }/*from   w  w w .j a  v a  2s  .  co  m*/

    final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
    final Class<? extends Email> mailType;
    if (attachments != null && attachments.size() > 0) {
        mailType = HtmlEmail.class;
    } else {
        mailType = this.getMailType(templatePath);
    }
    final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType);

    for (final InternetAddress address : recipients) {
        try {
            // Get a new email per recipient to avoid duplicate attachments
            Email email = getEmail(mailTemplate, mailType, emailParams);
            email.setTo(Collections.singleton(address));

            if (attachments != null && attachments.size() > 0) {
                for (Map.Entry<String, DataSource> entry : attachments.entrySet()) {
                    ((HtmlEmail) email).attach(entry.getValue(), entry.getKey(), null);
                }
            }

            messageGateway.send(email);
        } catch (Exception e) {
            failureList.add(address);
            log.error("Error sending email to [ " + address + " ]", e);
        }
    }

    return failureList;
}

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

/**
 * DOCUMENT ME!//w  w  w. j  a va2  s .  c  om
 *
 * @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!/*w  ww. j  av  a 2  s .  co  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:org.openhab.binding.mail.internal.MailBuilder.java

/**
 * Build the Mail/*from  w  ww.  j  a  v a2s .  c  o  m*/
 *
 * @return instance of Email
 * @throws EmailException if something goes wrong
 */
public Email build() throws EmailException {
    Email mail;

    if (attachmentURLs.isEmpty() && attachmentFiles.isEmpty() && html.isEmpty()) {
        // text mail without attachments
        mail = new SimpleEmail();
        if (!text.isEmpty()) {
            mail.setMsg(text);
        }
    } else if (html.isEmpty()) {
        // text mail with attachments
        MultiPartEmail multipartMail = new MultiPartEmail();
        if (!text.isEmpty()) {
            multipartMail.setMsg(text);
        }
        for (File file : attachmentFiles) {
            multipartMail.attach(file);
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            multipartMail.attach(attachment);
        }
        mail = multipartMail;
    } else {
        // html email
        HtmlEmail htmlMail = new HtmlEmail();
        if (!text.isEmpty()) {
            // alternate text supplied
            htmlMail.setTextMsg(text);
            htmlMail.setHtmlMsg(html);
        } else {
            htmlMail.setMsg(html);
        }
        for (File file : attachmentFiles) {
            htmlMail.attach(new FileDataSource(file), "", "");
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            htmlMail.attach(attachment);
        }
        mail = htmlMail;
    }

    mail.setTo(recipients);
    mail.setSubject(subject);

    if (!sender.isEmpty()) {
        mail.setFrom(sender);
    }

    return mail;
}

From source file:org.pepstock.jem.notify.engine.EmailNotifier.java

/**
 * This method sends an <code>Email</code>. <br>
 * It sets in the parameter <code>Email</code> the properties of the
 * parameter <code>JemEmail</code>: From User Email Address, From User Name,
 * subject, text, email destination addresses. <br>
 * It sets in the parameter <code>Email</code> the Email Server property and
 * the optional <code>SMTP</code> port, the properties that indicates if it
 * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and
 * password for <code>SMTP</code> server authentication if needed, the
 * optional bounce address, the subject, the text, and the recipients of the
 * email.//from   w w  w  .j a v  a  2s . c o  m
 * 
 * @param email the <code>JemEmail</code> with the properties of the email
 *            to be sent.
 * @param sendingEmail the real <code>Email</code> that will be sent.
 * @see JemEmail
 * @see Email
 * @throws SendMailException if an error occurs.
 */
private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException {
    try {
        sendingEmail.setHostName(this.emailServer);
        if (this.smtpPort != NO_SMTP_PORT) {
            sendingEmail.setSmtpPort(this.smtpPort);
        }
        sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName());
        if (email.hasSubject()) {
            sendingEmail.setSubject(email.getSubject());
        } else {
            // log no subject
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject");
        }
        if (email.hasText()) {
            sendingEmail.setMsg(email.getText());
        } else {
            // log no text message
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message");
        }
        sendingEmail.setTo(email.getAllToEmailAddresses());
        if (null != this.bounceAddress) {
            sendingEmail.setBounceAddress(this.bounceAddress);
        }
        sendingEmail.setSentDate(new Date());
        sendingEmail.setSSL(this.isSSL);
        sendingEmail.setTLS(this.isTLS);
        if (null != this.authenticationUserId && null != this.authenticationPassword) {
            sendingEmail.setAuthenticator(
                    new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword));
        }
        sendingEmail.send();
        LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email);
    } catch (EmailException eEx) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email);
        throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx);
    }
}

From source file:org.vas.mail.MailWorker.java

void send(Mail mail) {
    if (logger.isTraceEnabled()) {
        logger.trace("New mail to send - {}", mail.subject);
    }//from   ww  w.  j  a  va2 s.c  om

    Email email = smtp.emptyEmail();
    email.setSubject(mail.subject);
    try {
        email.setFrom(mail.from);
        email.setTo(Arrays.asList(new InternetAddress(mail.to)));
        email.setMsg(mail.body);

        if (logger.isDebugEnabled()) {
            logger.debug("Send mail {}", mail.subject);
        }

        email.send();
    } catch (EmailException | AddressException e) {
        throw new RuntimeException(e);
    }
}