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

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

Introduction

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

Prototype

public Email addTo(final String email) throws EmailException 

Source Link

Document

Add a recipient TO to the email.

Usage

From source file:org.jevis.jealarm.AlarmHandler.java

/**
 * Send the Alarm mail//  w ww  . j a va 2s  .  c  o m
 *
 * @param conf
 * @param alarm
 * @param body
 */
public void sendAlarm(Config conf, Alarm alarm, String body) {
    try {
        HtmlEmail email = new HtmlEmail();

        //            Email email = new SimpleEmail();
        email.setHostName(conf.getSmtpServer());
        email.setSmtpPort(conf.getSmtpPort());
        email.setAuthenticator(new DefaultAuthenticator(conf.getSmtpUser(), conf.getSmtpPW()));
        email.setSSLOnConnect(conf.isSmtpSSL());
        email.setFrom(conf.smtpFrom);
        email.setSubject(alarm.getSubject());

        for (String recipient : alarm.getRecipient()) {
            email.addTo(recipient);
        }

        for (String bcc : alarm.getBcc()) {
            email.addBcc(bcc);
        }
        email.setHtmlMsg(body);

        email.send();
        System.out.println("Alarm send: " + alarm.getSubject());
    } catch (Exception ex) {
        System.out.println("cound not send Email");
        ex.printStackTrace();
    }

}

From source file:org.jkandasa.email.blaster.EmailUtils.java

public static void sendEmail(AppProperties appProperties, Address address) throws EmailException, IOException {
    HtmlEmail email = initializeEmail(appProperties);
    StringBuilder attachmentBuilder = new StringBuilder();

    String[] attachments = appProperties.getAttachments().split(",");
    for (String attachment : attachments) {
        File img = new File(attachment);
        if (appProperties.isEmbeddedAttachments()) {
            attachmentBuilder.append("<br><img src=cid:").append(email.embed(img)).append(">");
        } else {//from   w  ww. j  av a 2  s  . co m
            email.attach(img);
        }
    }

    email.setSubject(getSubject(appProperties, address));
    email.setHtmlMsg(getMessage(appProperties, address).replaceAll(ATTACHMENTS, attachmentBuilder.toString()));
    email.addTo(address.getEmails().split(EMAIL_SEPARATOR));
    String sendReturn = email.send();
    _logger.debug("Send Status:[{}]", sendReturn);
    _logger.debug("Email successfully sent to [{}]", address);
}

From source file:org.meerkat.network.MailManager.java

/**
 * sendEmail/*  w  w w .ja  v a 2s  .  c  o m*/
 * @param subject
 * @param message
 */
public final void sendEmail(String subject, String message) {
    this.refreshSettings();

    HtmlEmail email = new HtmlEmail();
    email.setHostName(getSMTPServer());
    email.setSmtpPort(Integer.valueOf(getSMTPPort()));
    email.setSubject(subject);
    try {
        email.setHtmlMsg(message);
    } catch (EmailException e2) {
        log.error("Error in mail message. ", e2);
    }

    // SMTP security
    String security = getSMTPSecurity();
    if (security.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (security.equalsIgnoreCase("SSL/TLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(getSMTPPort()));
    }
    email.setAuthentication(getSMTPUser(), getSMTPPassword());

    try {
        String[] toList = getTO().split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        log.error("EmailException: addTo(" + getTO() + "). " + e1.getMessage());
    }

    try {
        email.setFrom(getFROM());
    } catch (EmailException e1) {
        log.error("EmailException: setFrom(" + getFROM() + "). " + e1.getMessage());
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        log.error("Failed to send email!", e);
    }
}

From source file:org.meerkat.network.MailManager.java

/**
 * testEmailSettingsFromWebService// w  w w .j  a v  a2  s.co  m
 * @param from
 * @param to
 * @param smtpServer
 * @param smtpPort
 * @param smtpSecurity
 * @param smtpUser
 * @param smtpPassword
 * @return
 */
public final String sendTestEmailSettingsFromWebService(String from, String to, String smtpServer,
        String smtpPort, String smtpSecurity, String smtpUser, String smtpPassword) {
    String resultString = "OK";
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtpServer);
    email.setSmtpPort(Integer.valueOf(smtpPort));
    email.setSubject(testSubject);
    try {
        email.setHtmlMsg(testMessage);
    } catch (EmailException e2) {
        resultString = e2.getMessage();
        return resultString;
    }

    // SMTP security
    if (smtpSecurity.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (smtpSecurity.equalsIgnoreCase("SSLTLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(smtpPort));
    }
    email.setAuthentication(smtpUser, smtpPassword);

    try {
        String[] toList = to.split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        resultString = "TO: " + e1.getMessage();
        return resultString;
    }

    try {
        email.setFrom(from);
    } catch (EmailException e1) {
        resultString = "FROM: " + e1.getMessage();
        return resultString;
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        resultString = e.getMessage();
        return resultString;
    }

    return resultString;
}

From source file:org.ng200.openolympus.services.EmailService.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
public void sendEmail(String emailAddress, String subject, String view, String alternativeText,
        Map<String, Object> variables) throws MessagingException, EmailException {
    final Context ctx = new Context();
    ctx.setVariables(variables);//from   w  w w . j  a v  a  2s.c o m

    final HtmlEmail email = new HtmlEmail();
    email.setHostName(this.emailHost);
    email.setSmtpPort(this.emailHostPort);
    email.setAuthenticator(new DefaultAuthenticator(this.emailLogin, this.emailPassword));
    email.setSSL(true);
    email.setFrom(this.emailLogin);
    email.setSubject(subject);

    final String htmlContent = this.templateEngine.process(view, ctx);

    email.setHtmlMsg(htmlContent);

    email.setTextMsg(alternativeText);

    email.addTo(emailAddress);
    email.send();

}

From source file:org.opencron.server.service.NoticeService.java

public void sendMessage(List<User> users, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(false);/*from   ww  w  .  j a  v a 2s  . c  o  m*/
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;

    Config config = configService.getSysConfig();
    try {
        log.setType(Opencron.MsgType.EMAIL.getValue());
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("opencron");
        email.setHtmlMsg(msgToHtml(content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));
            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);
            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(Opencron.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        for (User user : users) {
            //??
            log.setUserId(user.getUserId());
            log.setReceiver(user.getUserName());
            homeService.saveLog(log);
        }
    }

}

From source file:org.teknux.dropbitz.service.email.EmailSender.java

public void sendEmail(DropbitzEmail dropbitzEmail, HtmlEmail email) throws EmailServiceException {
    logger.debug("Send email...");

    if (dropbitzEmail == null) {
        throw new EmailServiceException("DropbitzEmail can not be null");
    }/*from   w  w  w. j a  v a 2s.c  om*/
    if (email == null) {
        throw new EmailServiceException("HtmlEmail can not be null");
    }

    //Global Configuration
    email.setHostName(Objects.requireNonNull(config.getEmailHost(), "Email Host is required"));
    email.setSmtpPort(config.getEmailPort());
    if ((config.getEmailUsername() != null && !config.getEmailUsername().isEmpty())
            || (config.getEmailPassword() != null && !config.getEmailPassword().isEmpty())) {
        email.setAuthentication(config.getEmailUsername(), config.getEmailPassword());
    }
    email.setSSLOnConnect(config.isEmailSsl());

    email.setSubject(dropbitzEmail.getSubject());
    try {
        email.setFrom(Objects.requireNonNull(dropbitzEmail.getEmailFrom(), "Email From is required"));
        if (dropbitzEmail.getEmailTo() == null || dropbitzEmail.getEmailTo().size() == 0) {
            throw new EmailServiceException("Email To is required");
        }
        email.addTo(dropbitzEmail.getEmailTo().toArray(new String[dropbitzEmail.getEmailTo().size()]));
        email.setHtmlMsg(Objects.requireNonNull(dropbitzEmail.getHtmlMsg(), "HtmlMsg is required"));
        if (dropbitzEmail.getTextMsg() != null) {
            email.setTextMsg(dropbitzEmail.getTextMsg());
        }
        email.send();

        logger.trace(MessageFormat.format("Email sent from [{0}] to [{1}]", dropbitzEmail.getEmailFrom(),
                String.join(",", dropbitzEmail.getEmailTo())));
    } catch (EmailException e) {
        throw new EmailServiceException("Email not sent", e);
    }
}

From source file:org.vulpe.commons.util.VulpeEmailUtil.java

/**
 * Send Mail to many recipients./*from   www.  ja v a  2s.  c o m*/
 *
 * @param recipients
 *            Recipients
 * @param subject
 *            Subject
 * @param body
 *            Body
 * @throws VulpeSystemException
 *             exception
 */
public static boolean sendMail(final String[] recipients, final String subject, final String body) {
    boolean sended = true;
    if (!checkValidEmail(recipients)) {
        LOG.error("Invalid mails: " + recipients);
        sended = false;
    }
    if (isDebugEnabled) {
        LOG.debug("Entering in sendMail...");
        for (int i = 0; i < recipients.length; i++) {
            LOG.debug("recipient: " + recipients[i]);
        }
        LOG.debug("subject: " + subject);
        LOG.debug("body: " + body);
    }
    try {
        final ResourceBundle bundle = ResourceBundle.getBundle("mail");
        if (bundle != null) {
            final HtmlEmail mail = new HtmlEmail();
            String mailFrom = "";
            if (bundle.containsKey("mail.smtp.auth") && Boolean.valueOf(bundle.getString("mail.smtp.auth"))) {
                final String username = bundle.getString("mail.smtp.user");
                final String password = bundle.getString("mail.smtp.password");
                mail.setAuthentication(username, password);
            }
            if (bundle.containsKey("mail.from")) {
                mailFrom = bundle.getString("mail.from");
            }
            mail.setFrom(mailFrom);
            for (final String recipient : recipients) {
                mail.addTo(recipient);
            }
            mail.setHostName(bundle.getString("mail.smtp.host"));
            final String port = bundle.getString("mail.smtp.port");
            mail.setSmtpPort(Integer.valueOf(port));
            if (bundle.containsKey("mail.smtp.starttls.enable")
                    && Boolean.valueOf(bundle.getString("mail.smtp.starttls.enable"))) {
                mail.setTLS(true);
                mail.setSSL(true);
                if (bundle.containsKey("mail.smtp.socketFactory.port")) {
                    String factoryPort = bundle.getString("mail.smtp.socketFactory.port");
                    mail.setSslSmtpPort(factoryPort);
                }
            }
            String encoding = "UTF-8";
            if (bundle.containsKey("mail.encode")) {
                encoding = bundle.getString("mail.encode");
            }
            mail.setCharset(encoding);
            mail.setSubject(subject);
            mail.setHtmlMsg(body);
            mail.send();
        } else {
            LOG.error("Send Mail properties not setted");
            sended = false;
        }
    } catch (Exception e) {
        LOG.error("Error on send mail", e);
        sended = false;
    }
    LOG.debug("Out of sendMail...");
    return sended;
}

From source file:tilda.utils.MailUtil.java

/**
 * /*from w w w  . j ava2s . co  m*/
 * @param SmtpInfo A string such as smtp.mydomain.com:422:ssl to connect to an SMTP server
 * @param From the user ID used to send emails from
 * @param Password The password for the account we send emails from
 * @param To Destination email(s)
 * @param Cc CC email(s)
 * @param Bcc BCC emails(s)
 * @param Subject The Subject
 * @param Message The message (HTML allowed)
 * @param Urgent Whether to send the message as urgent or not.
 * @return
 */
public static boolean send(String SmtpInfo, String From, String Password, String[] To, String[] Cc,
        String[] Bcc, String Subject, String Message, boolean Urgent) {
    String LastAddress = null;
    try {
        HtmlEmail email = new HtmlEmail();

        String[] parts = SmtpInfo.split(":");
        email.setHostName(parts[0]);
        if (parts.length > 1) {
            if (parts.length > 2 && parts[2].equalsIgnoreCase("ssl") == true) {
                email.setSslSmtpPort(parts[1]);
                email.setSSLOnConnect(true);
            } else {
                email.setSmtpPort(Integer.parseInt(parts[1]));
            }
        }

        email.setAuthentication(From, Password);
        email.setSubject(Subject);

        LOG.debug("Sending an email '" + email.getSubject() + "'.");
        if (To != null)
            for (String s : To) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addTo(s);
            }
        if (Cc != null)
            for (String s : Cc) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addCc(s);
            }
        if (Bcc != null)
            for (String s : Bcc) {
                if (TextUtil.isNullOrEmpty(s) == true)
                    continue;
                LastAddress = s;
                email.addBcc(s);
            }
        if (LastAddress == null) {
            LOG.debug("No recipient. Not sending anything.");
            return true;
        }
        email.setFrom(From);
        LastAddress = From;
        email.setHtmlMsg(Message);
        if (Urgent == true)
            email.addHeader("X-Priority", "1");
        LastAddress = null;
        email.send();
        return true;
    } catch (EmailException E) {
        if (LastAddress != null)
            LOG.debug("Email address '" + LastAddress + "' seems to be invalid.");
        LOG.error(E);
        return false;
    }
}

From source file:util.Log.java

public static void relatarExceptionEmail(String className, String exception, String logPath) {
    /*//from w  w w  . j  a  va2s.c  om
     * Para compreender melhor acesse esse site:
     * http://www.botecodigital.info/java/enviando-e-mail-em-java-com-api-
     * commons-email-da-apache/
     */
    HtmlEmail email = new HtmlEmail();
    email.setSSLOnConnect(true);
    email.setHostName("smtp.gmail.com");
    email.setSslSmtpPort("465");
    email.setAuthenticator(new DefaultAuthenticator("jjsoftwares10@gmail.com", "jean1420"));
    try {
        email.setFrom("jjsoftwares10@gmail.com", "Software da clinica");
        email.setSubject("Exceo ocorrida no app da clinica");
        StringBuilder msg = new StringBuilder();
        msg.append("<h1 style=\"text-align: center;\">Excecao Ocorrida</h1>");
        msg.append("<p><strong>Na Classe: " + className + " </strong></p>");
        msg.append("<p><strong>Data e Horario do ocorrido: "
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:s"))
                + "</strong></p>");
        msg.append("<h2 style=\"text-align: center;\"><strong>Excecao</strong></h2>");
        msg.append("<p><span style=\"color: #ff0000;\">" + exception + "</span></p>");
        msg.append("<p><strong>Segue anexo com detalhes</strong></p>");
        /*Enviando o anexo com detalhes da exceo*/
        File arqLog = new File(logPath);
        if (arqLog.exists()) {
            EmailAttachment anexo = new EmailAttachment();
            anexo.setPath(logPath);
            anexo.setDisposition(EmailAttachment.ATTACHMENT);
            anexo.setName(arqLog.getName());
            email.attach(anexo);
        }
        /*enviando*/
        email.setHtmlMsg(msg.toString());
        email.addTo("jeandersonfju@gmail.com");
        email.addTo("jeff-assis@hotmail.com");
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();

    }
}