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

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

Introduction

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

Prototype

public Email setFrom(final String email) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address.

Usage

From source file:org.apache.unomi.plugins.mail.actions.SendMailAction.java

public int execute(Action action, Event event) {
    String from = (String) action.getParameterValues().get("from");
    String to = (String) action.getParameterValues().get("to");
    String cc = (String) action.getParameterValues().get("cc");
    String bcc = (String) action.getParameterValues().get("bcc");
    String subject = (String) action.getParameterValues().get("subject");
    String template = (String) action.getParameterValues().get("template");

    ST stringTemplate = new ST(template);
    stringTemplate.add("profile", event.getProfile());
    stringTemplate.add("event", event);
    // load your HTML email template
    String htmlEmailTemplate = stringTemplate.render();

    // define you base URL to resolve relative resource locations
    try {/*  w  w  w .ja va2 s  .  co  m*/
        new URL("http://www.apache.org");
    } catch (MalformedURLException e) {
        //
    }

    // create the email message
    HtmlEmail email = new ImageHtmlEmail();
    // email.setDataSourceResolver(new DataSourceResolverImpl(url));
    email.setHostName(mailServerHostName);
    email.setSmtpPort(mailServerPort);
    email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword));
    email.setSSLOnConnect(mailServerSSLOnConnect);
    try {
        email.addTo(to);
        email.setFrom(from);
        if (cc != null && cc.length() > 0) {
            email.addCc(cc);
        }
        if (bcc != null && bcc.length() > 0) {
            email.addBcc(bcc);
        }
        email.setSubject(subject);

        // set the html message
        email.setHtmlMsg(htmlEmailTemplate);

        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send mail", e);
    }

    return EventService.NO_CHANGE;
}

From source file:org.cerberus.service.email.impl.sendMail.java

public static void sendHtmlMail(String host, int port, String body, String subject, String from, String to,
        String cc) throws Exception {

    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(port);/*  w ww.  j  a  va 2s . c  o m*/
    email.setDebug(false);
    email.setHostName(host);
    email.setFrom(from);
    email.setSubject(subject);
    email.setHtmlMsg(body);

    String[] destinataire = to.split(";");

    for (int i = 0; i < destinataire.length; i++) {
        String name;
        String emailaddress;
        if (destinataire[i].contains("<")) {
            String[] destinatairedata = destinataire[i].split("<");
            name = destinatairedata[0].trim();
            emailaddress = destinatairedata[1].replace(">", "").trim();
        } else {
            name = "";
            emailaddress = destinataire[i];
        }
        email.addTo(emailaddress, name);
    }

    String[] copy = cc.split(";");

    for (int i = 0; i < copy.length; i++) {
        String namecc;
        String emailaddresscc;
        if (copy[i].contains("<")) {
            String[] copydata = copy[i].split("<");
            namecc = copydata[0].trim();
            emailaddresscc = copydata[1].replace(">", "").trim();
        } else {
            namecc = "";
            emailaddresscc = copy[i];
        }
        email.addCc(emailaddresscc, namecc);
    }

    email.setTLS(true);

    email.send();

}

From source file:org.jcronjob.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    try {/*from  w  w w.j a  v  a 2s. com*/
        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("cronjob");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();

        Log log = new Log();
        log.setType(0);
        log.setWorkerId(workId);
        log.setMessage(content);
        for (String receiver : emailAddress.split(",")) {
            log.setReceiver(receiver);
            log.setSendTime(new Date());
            homeService.saveLog(log);
        }
        log.setType(1);
        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.setReceiver(mobile);
            log.setResult(message);
            log.setSendTime(new Date());
            homeService.saveLog(log);
            logger.info(message);

        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

}

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

/**
 * Send the Alarm mail//from w w  w .j  a va  2  s.  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 HtmlEmail initializeEmail(AppProperties appProperties) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(appProperties.getSmtpHost());
    email.setSmtpPort(Integer.valueOf(appProperties.getSmtpPort()));
    if (appProperties.getUsername() != null && appProperties.getUsername().length() > 0) {
        email.setAuthenticator(/*w  ww  . ja  v a 2  s.  c  o  m*/
                new DefaultAuthenticator(appProperties.getUsername(), appProperties.getPassword()));
    }
    email.setSSLOnConnect(appProperties.isEnableSSL());
    email.setFrom(appProperties.getFromAddress());
    return email;
}

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

/**
 * sendEmail/*w ww  .java 2 s.co  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/*from  w  w  w .  j a  v a  2 s. com*/
 * @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 ava 2 s. c  om

    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);/* ww  w.  j  a v a  2  s. 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");
    }/*ww w.j  a  v a 2  s.  co m*/
    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);
    }
}