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

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

Introduction

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

Prototype

public Email addTo(final String... emails) throws EmailException 

Source Link

Document

Add a list of TO recipients to the email.

Usage

From source file:org.openhab.io.net.actions.Mail.java

/**
 * Sends an email with attachment via SMTP
 * /*  w  ww.j  a v  a2  s . c  o m*/
 * @param to the email address of the recipient
 * @param subject the subject of the email
 * @param message the body of the email
 * @param attachmentUrl a URL string of the content to send as an attachment
 * 
 * @return <code>true</code>, if sending the email has been successful and 
 * <code>false</code> in all other cases.
 */
static public boolean sendMail(String to, String subject, String message, String attachmentUrl) {
    boolean success = false;
    if (initialized) {
        Email email = new SimpleEmail();
        if (attachmentUrl != null) {
            // Create the attachment
            try {
                email = new MultiPartEmail();
                EmailAttachment attachment = new EmailAttachment();
                attachment.setURL(new URL(attachmentUrl));
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName("Attachment");
                ((MultiPartEmail) email).attach(attachment);
            } catch (MalformedURLException e) {
                logger.error("Invalid attachment url.", e);
            } catch (EmailException e) {
                logger.error("Error adding attachment to email.", e);
            }
        }

        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            email.setFrom(from);
            email.addTo(to);
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.isEmpty(message))
                email.setMsg(message);
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + ".", e);
        }
    } else {
        logger.error(
                "Cannot send e-mail because of missing configuration settings. The current settings are: "
                        + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'",
                new String[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}

From source file:org.ow2.frascati.akka.fabric.peakforecast.lib.EmailImpl.java

@Override
public void send(String message) {

    try {//from  w ww .ja  v  a 2s.  c  om
        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        //email.setAuthenticator(new DefaultAuthenticator("username", "password"));
        email.setAuthenticator(new DefaultAuthenticator("fouomenedaniel@gmail.com", "motdepasse"));
        email.setSSLOnConnect(true);
        email.setFrom("fouomenedaniel@gmail.com");
        email.setSubject("Alert PeakForecast");
        email.setMsg(message);
        String listtabmail[] = listEmails.split(" ");
        for (int i = 0; i < listtabmail.length; i++) {

            email.addTo(listtabmail[i]);

        }
        email.send();
        System.out.println("Message Email envoy !!!");
    } catch (EmailException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.paxml.bean.EmailTag.java

private Email createEmail(Collection<String> to, Collection<String> cc, Collection<String> bcc)
        throws EmailException {
    Email email;
    if (attachment == null || attachment.isEmpty()) {
        email = new SimpleEmail();
    } else {/*from w  w  w.  j  a  v a  2s .c  o m*/
        MultiPartEmail mpemail = new MultiPartEmail();
        for (Object att : attachment) {
            mpemail.attach(makeAttachment(att.toString()));
        }
        email = mpemail;
    }

    if (StringUtils.isNotEmpty(username)) {
        String pwd = null;
        if (password instanceof Secret) {
            pwd = ((Secret) password).getDecrypted();
        } else if (password != null) {
            pwd = password.toString();
        }
        email.setAuthenticator(new DefaultAuthenticator(username, pwd));
    }

    email.setHostName(findHost());
    email.setSSLOnConnect(ssl);
    if (port > 0) {
        if (ssl) {
            email.setSslSmtpPort(port + "");
        } else {
            email.setSmtpPort(port);
        }
    }
    if (replyTo != null) {
        for (Object r : replyTo) {
            email.addReplyTo(r.toString());
        }
    }
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(text);
    if (to != null) {
        for (String r : to) {
            email.addTo(r);
        }
    }
    if (cc != null) {
        for (String r : cc) {
            email.addCc(r);
        }
    }
    if (bcc != null) {
        for (String r : bcc) {
            email.addBcc(r);
        }
    }
    email.setSSLCheckServerIdentity(sslCheckServerIdentity);
    email.setStartTLSEnabled(tls);
    email.setStartTLSRequired(tls);
    return email;
}

From source file:org.polymap.rhei.um.operations.NewPasswordOperation.java

@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    try {/*w  ww.j a v a 2  s. c o  m*/
        // password hash
        PasswordEncryptor encryptor = PasswordEncryptor.instance();
        String password = encryptor.createPassword(8);
        String hash = encryptor.encryptPassword(password);
        user.passwordHash().set(hash);
        log.debug("Neues Passwort: " + password + " -> " + hash);

        // username <= email
        String username = user.email().get();
        assert username != null && username.length() > 0;
        user.username().set(username);
        log.info("username: " + user.username().get());

        // commit
        UserRepository.instance().commitChanges();

        // XXX email
        String salu = user.salutation().get() != null ? user.salutation().get() : "";
        String header = (salu.equalsIgnoreCase("Herr") ? "r Herr " : " ") + salu + " " + user.name().get();
        Email email = new SimpleEmail();
        email.setCharset("ISO-8859-1");
        email.addTo(username).setSubject(i18n.get("emailSubject"))
                .setMsg(i18n.get("email", header, username, password));

        EmailService.instance().send(email);

        return Status.OK_STATUS;
    } catch (EmailException e) {
        throw new ExecutionException(i18n.get("errorMsg", e.getLocalizedMessage()), e);
    }
}

From source file:org.polymap.rhei.um.operations.NewUserOperation.java

@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    try {/*from  ww  w .  j  ava  2s  .c  o m*/
        // password hash
        PasswordEncryptor encryptor = PasswordEncryptor.instance();
        String password = encryptor.createPassword(8);
        String hash = encryptor.encryptPassword(password);
        user.passwordHash().set(hash);

        // username <= email
        String username = user.email().get();
        assert username != null && username.length() > 0;
        user.username().set(username);
        log.info("username: " + user.username().get());

        // commit
        UserRepository.instance().commitChanges();

        String salu = user.salutation().get() != null ? user.salutation().get() : "";
        String header = (salu.equalsIgnoreCase("Herr") ? "r " : " ") + salu + " " + user.name().get();
        Email email = new SimpleEmail();
        email.setCharset("ISO-8859-1");
        email.addTo(username).setSubject(emailSubject)
                .setMsg(new MessageFormat(emailContent, Polymap.getSessionLocale())
                        .format(new Object[] { header, username, password }));
        //                    .setMsg( i18n.get( "email", header, username, password ) );

        EmailService.instance().send(email);

        return Status.OK_STATUS;

    } catch (EmailException e) {
        throw new ExecutionException(i18n.get("errorMsg", e.getLocalizedMessage()), e);
    }
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;/*from w  w  w  . ja v a  2  s.c om*/
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

@Override
public void sendVerification(final EmailConfiguration configuration, final String address)
        throws EmailException {
    checkNotNull(configuration);//  w ww.j ava2  s .com
    checkNotNull(address);

    Email mail = new SimpleEmail();
    mail.setSubject("Email configuration verification");
    mail.addTo(address);
    mail.setMsg("Verification successful");
    mail = apply(configuration, mail);
    mail.send();
}

From source file:org.sonatype.nexus.internal.scheduling.NexusTaskFailureAlertEmailSender.java

private void sendEmail(final String address, final String taskId, final String taskName, final Throwable cause)
        throws Exception {
    Email mail = new SimpleEmail();
    mail.setSubject("Task execution failure");
    mail.addTo(address);

    // FIXME: This should ideally render a user-configurable template
    StringWriter buff = new StringWriter();
    PrintWriter out = new PrintWriter(buff);
    if (taskId != null) {
        out.format("Task ID: %s%n", taskId);
    }/*  w  w  w .  j a v  a 2s . com*/
    if (taskName != null) {
        out.format("Task Name: %s%n", taskName);
    }
    if (cause != null) {
        out.println("Stack-trace:");
        cause.printStackTrace(out);
    }
    mail.setMsg(buff.toString());

    emailManager.get().send(mail);
}

From source file:org.ygl.plexc.PlexcLibrary.java

/**
 * Sends an email or text notification upon successful access.
 * @param requester// w ww. ja  va 2  s.c  o  m
 * @return
 */
public boolean notify_1(Term requester) {
    final String user = getCurrentUser();
    final String host = "localhost";
    final String subject = "PlexC access notification";
    final String text = String.format("%s, %s has been granted access to your location.", user,
            requester.getTerm().toString());

    Email email = new SimpleEmail();
    email.setSubject(subject);
    email.setHostName(host);
    email.setSmtpPort(465);

    try {
        email.setFrom("noreply@plexc.com");
        email.setMsg(text);
        email.addTo(user);
        email.send();
    } catch (EmailException e) {
        LOG.warn(e.getMessage());
        return false;
    }
    return true;
}

From source file:paquetes.AlertSchedule.java

@Schedule(hour = "8", dayOfWeek = "*", info = "Todos los dias a las 8:00 a.m.")
//@Schedule(second = "*", minute = "*/10", hour = "*", persistent= true, info = "cada 10 minutos")

public void performTask() throws EmailException {

    long timeInit = System.currentTimeMillis();
    ConfiguracionMail();/*from  w  w  w  .  jav  a  2 s .co m*/

    log.info(":. Inicio TareaProgramada cada dia");

    try {
        timeInit = System.currentTimeMillis();

        obtenerAlertas();

        // Luego de obtener las alertas las recorremos para conformar cada uno de los selects de validacion
        alertas.stream().forEach((ale) -> {

            id_ale = ale.getId_ale();
            llenarAlertasUsuarios(ale.getId_ale());
            verificarPorTipoAlerta(ale);
            nom_tip_ale = ale.getNom_tip_ale();

            logale.stream().forEach((lgal) -> {

                try {
                    Email email = new SimpleEmail();
                    email.setHostName(this.hostname);
                    email.setSmtpPort(Integer.parseInt(this.smtp_port));
                    email.setAuthenticator(new DefaultAuthenticator(this.user, this.pass));
                    // TLS agregado para server AWS Se quita comentario a setSSL.
                    email.setStartTLSEnabled(true);
                    email.setStartTLSRequired(true);

                    // Comentariado para funcionar con Gmail
                    //email.setSSLOnConnect(true);

                    email.setFrom(this.remitente);
                    email.setSubject(nom_tip_ale);
                    email.setMsg(lgal.getAle_des());

                    alertasusuarios.stream().forEach((mailDestino) -> {
                        try {
                            email.addTo(mailDestino.getMailusu());
                        } catch (Exception e) {
                            System.out.println("Error en la obtencion de destinatarios. " + e.getMessage());
                        }
                    });

                    email.send();
                } catch (Exception e) {
                    System.out.println("Error en la conformacion del correo. " + e.getMessage());
                }
            });
        });
    } catch (Exception e) {
        log.error("Error en la tarea programada");
        log.info(e);
    }

    long time = System.currentTimeMillis();
    time = System.currentTimeMillis() - timeInit;
    log.info(":. Fin tarea programada. Tiempo de proceso = " + time);

}