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:br.com.mysqlmonitor.monitor.Monitor.java

private void enviarEmailDBA() {
    try {/*from w  w w  . j  av  a2  s.com*/
        if (logs.length() != 0) {
            System.out.println("Divergencias: " + logs);
            for (Usuario usuario : usuarioDAO.findAll()) {
                System.out.println("Enviando email para: " + usuario.getNome());
                HtmlEmail email = new HtmlEmail();
                email.setHostName("smtp.googlemail.com");
                email.setSmtpPort(465);
                email.setAuthenticator(new DefaultAuthenticator("mysqlmonitorsuporte", "4rgvr6RM"));
                email.setSSL(true);
                email.setFrom("mysqlmonitorsuporte@gmail.com");
                email.setSubject("Log Mysql Monitor");
                email.setHtmlMsg(logs.toString());
                email.addTo(usuario.getEmail());
                email.send();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {//from w  ww  . j a v a 2 s .  c o m

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        URL url = linkBoleto;//new URL(linkBoleto);
        String cid = email.embed(url, new BusinessDelegate().getMensagem(new BigDecimal(61)).getAssunto());

        // localizando a mensagem
        //Mensagem msg = new Mensagem();
        //msg = new BusinessDelegate().getMensagem(mensagemId);

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        body += (this.bodyProfissional);
        body += ("Fa&ccedil;a Download do Boleto para pagamento: - <a href=" + url
                + " target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        body += "<img src=\"cid:" + cid + "\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(null);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

/**
*
* @param destinatario/*from w w  w  .  ja  v a  2s. com*/
* @param nome
* @param assunto
* @throws IOException
*/

public void sendingHtml(String destinatario, String nome, String assunto, int tipoId) throws IOException {
    try {

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        //email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        // URL url = linkBoleto;//new URL(linkBoleto);
        //String cid = email.embed(url, "Congresso TRT 15");

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        if (tipoId == 1) {
            body += (this.bodyProfissional);
        } else if (tipoId == 2) {
            body += (this.bodyServidor);
        } else if (tipoId == 3) {
            body += (this.bodyMagistrado);
        } else if (tipoId == 4) {
            body += (this.bodyEstudante);
        } else {
            body += "Congresso TRT";
        }

        // body+=("Faa Download do Boleto para pagamento: - <a href="+url+" target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        //body+="<img src=\"cid:"+cid+"\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(CONTENT_TYPE);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        // utils.Logger.getLogger("Erro ao enviar Email. "+tipoId+" - "+ex.toString(),tipoId);
        // utils.Logger.getLoggerPessoaFisica("Erro ao enviar email - sending html:"+ex.getMessage());
    }

}

From source file:enviocorreo.EnviadorCorreo.java

/**
 * Enva un correo electrnico. Utiliza la biblioteca Apache Commons Email,
 * accesible va <a href="https://commons.apache.org/proper/commons-email/">https://commons.apache.org/proper/commons-email/</a>
 *
 * @param destinatario//w ww  . j  a  v  a 2 s .  c o m
 * @param asunto
 * @param mensaje
 * @return
 */
public boolean enviarCorreoE(String destinatario, String asunto, String mensaje) {
    boolean resultado = false;

    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setSmtpPort(puerto);
    email.setAuthenticator(new DefaultAuthenticator(usuario, password));

    if (isGmail) {
        email.setSSLOnConnect(true);
    } else {
        email.setStartTLSEnabled(true);
    }

    try {
        email.setFrom(usuario + "<dominio del correo>");
        email.setSubject(asunto);
        email.setHtmlMsg(mensaje);
        email.addTo(destinatario);
        email.send();
        resultado = true;
    } catch (EmailException eme) {
        mensaje = "Ocurri un error al hacer el envo de correo.";
        mensajeError = eme.toString();
    }

    return resultado;
}

From source file:com.jredrain.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(0);/*from  w ww .  j  a v  a  2  s .com*/
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;
    try {
        log.setType(RedRain.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("redrain");
        email.setHtmlMsg(msgToHtml(receiverId, 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(RedRain.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    }

}

From source file:br.com.atmatech.sac.controller.Email.java

public void emaiMassa(String smtp, String user, String password, Integer porta, Boolean ssl, Boolean tls,
        List<PessoaBeans> emailto, String emailfrom, String conteudo, String assunto)
        throws EmailException, MalformedURLException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtp); // o servidor SMTP para envio do e-mail
    Integer indice2 = 0;/*from   w w w.j ava  2 s  .c o  m*/
    Integer j = 0;
    for (int i = 0; (i < emailto.size()) && (i < 45); i++) {
        email.addTo(emailto.get(i).getEmail());//destinatario            
        indice2 = i;
    }
    while (j <= indice2) {
        emailto.remove(0);
        j++;
    }
    conteudo = conteudo.replaceAll("\n", "<p>");
    email.setFrom(emailfrom); // remetente        
    //email.addCc(emailfrom);
    email.setSubject(assunto);
    // configura a mensagem para o formato HTML        
    email.setHtmlMsg("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"
            + conteudo + "</html>");
    email.setAuthentication(user, password);
    email.setSmtpPort(porta);
    email.setSSL(ssl);
    email.setTLS(tls);
    email.send();
    if (emailto != null) {
        if (emailto.size() > 1) {
            emaiMassa(smtp, user, password, porta, ssl, tls, emailto, emailfrom, conteudo, assunto);
        }
    }

}

From source file:com.aquest.emailmarketing.web.service.SendEmail.java

/**
 * Send email.//from w w w  . ja  v a  2 s.  c  om
 *
 * @param broadcast the broadcast
 * @param emailConfig the email config
 * @param emailList the email list
 * @throws EmailException the email exception
 * @throws MalformedURLException the malformed url exception
 * @throws InterruptedException the interrupted exception
 */
@Async
public void sendEmail(Broadcast broadcast, EmailConfig emailConfig, EmailList emailList)
        throws EmailException, MalformedURLException, InterruptedException {

    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    // email configuration part
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(emailConfig.getPort());
    email.setHostName(emailConfig.getHostname());
    email.setAuthenticator(new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword()));
    email.setSSLOnConnect(emailConfig.isSslonconnect());
    email.setDebug(emailConfig.isDebug());
    email.setFrom(emailConfig.getFrom_address()); //ovde dodati i email from description

    System.out.println(emailList);
    HashMap<String, String> variables = processVariableService.ProcessVariable(emailList);

    for (String keys : variables.keySet()) {
        System.out.println("key:" + keys + ", value:" + variables.get(keys));
    }

    String processSubject = broadcast.getSubject();
    String newHtml = broadcast.getHtmlbody_embed();
    String newPlainText = broadcast.getPlaintext();

    for (String key : variables.keySet()) {
        processSubject = processSubject.replace("[" + key + "]", variables.get(key));
        System.out.println(key + "-" + variables.get(key));
        newHtml = newHtml.replace("[" + key + "]", variables.get(key));
        newPlainText = newPlainText.replace("[" + key + "]", variables.get(key));
    }
    System.out.println(processSubject);
    email.setSubject(processSubject);
    email.addTo(emailList.getEmail());

    String image = embeddedImageService.getEmbeddedImages(broadcast.getBroadcast_id()).getUrl();
    List<String> images = Arrays.asList(image.split(";"));
    for (int j = 0; j < images.size(); j++) {
        System.out.println(images.get(j));
    }
    for (int i = 0; i < images.size(); i++) {
        String id = email.embed(images.get(i), "Slika" + i);
        newHtml = newHtml.replace("[IMAGE:" + i + "]", "cid:" + id);
    }

    Config config = configService.getConfig("trackingurl");
    //DONE: Create jsp page for tracking server url
    String serverUrl = config.getValue();
    System.out.println(serverUrl);
    Base64 base64 = new Base64(true);

    Pattern pattern = Pattern.compile("<%tracking=(.*?)=tracking%>");
    Matcher matcher = pattern.matcher(newHtml);
    while (matcher.find()) {
        String url = matcher.group(1);
        System.out.println(url);
        logger.debug(url);
        String myEncryptedUrl = new String(base64.encode(url.getBytes()));

        String oldurl = "<%tracking=" + url + "=tracking%>";
        logger.debug(oldurl);
        System.out.println(oldurl);
        String newurl = serverUrl + "tracking?id=" + myEncryptedUrl;
        logger.debug(newurl);
        System.out.println(newurl);
        newHtml = newHtml.replace(oldurl, newurl);
    }
    //        System.out.println(newHtml);

    email.setHtmlMsg(newHtml);
    email.setTextMsg(newPlainText);
    try {
        System.out.println("A ovo ovde?");
        email.send();
        emailList.setStatus("SENT");
        emailList.setProcess_dttm(curTimestamp);
        emailListService.SaveOrUpdate(emailList);
    } catch (Exception e) {
        logger.error(e);
    }
    // time in seconds to wait between 2 mails
    TimeUnit.SECONDS.sleep(emailConfig.getWait());
}

From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTP.java

public ConfigurazioneSMTP() {

    this.setMargin(true);

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);//from w  ww  .  ja  v  a2 s.  c  o  m
    TextField smtpPort = new TextField("SMTP Port");
    smtpPort.setRequired(true);
    TextField smtpUser = new TextField("SMTP Username");
    smtpUser.setRequired(true);
    TextField smtpPwd = new TextField("SMTP Password");
    smtpPwd.setRequired(true);
    TextField pwdConf = new TextField("Conferma la Password");
    pwdConf.setRequired(true);
    CheckBox security = new CheckBox("Sicurezza del server");

    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        System.out.println("Carico file di configurazione");
        try {
            props.load(config);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    smtpHost.setValue(props.getProperty("smtp_host"));
    smtpUser.setValue(props.getProperty("smtp_user"));
    security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec")));

    Button salva = new Button("Salva i parametri");
    salva.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Salvo i parametri SMTP");
        if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid()
                && smtpPwd.getValue().equals(pwdConf.getValue())) {
            props.setProperty("smtp_host", smtpHost.getValue());
            props.setProperty("smtp_port", smtpPort.getValue());
            props.setProperty("smtp_user", smtpUser.getValue());
            props.setProperty("smtp_pwd", smtpPwd.getValue());
            props.setProperty("smtp_sec", security.getValue().toString());
            String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext()
                    .getRealPath("WEB-INF");
            File f = new File(webInfPath + "/config.properties");
            try {
                OutputStream o = new FileOutputStream(f);
                try {
                    props.store(o, "Prova");
                } catch (IOException ex) {
                    Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            Notification.show("Parametri salvati");
        } else {
            Notification.show("Ricontrolla i parametri");
        }

    });

    TextField emailTest = new TextField("Destinatario Mail di Prova");
    emailTest.setImmediate(true);
    emailTest.addValidator(new EmailValidator("Mail non valida"));

    Button test = new Button("Invia una mail di prova");
    test.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Invio della mail di prova");
        if (emailTest.isValid()) {
            try {
                System.out.println("Invio mail di prova a " + emailTest.getValue());
                HtmlEmail email = new HtmlEmail();
                email.setHostName(props.getProperty("smtp_host"));
                email.setSmtpPort(Integer.parseInt(props.getProperty("smtp_port")));
                email.setSSLOnConnect(Boolean.parseBoolean(props.getProperty("smtp_sec")));
                email.setAuthentication(props.getProperty("smtp_user"), props.getProperty("smtp_pwd"));
                email.setFrom("prova@prova.it");
                email.setSubject("Mail di prova");
                email.addTo(emailTest.getValue());
                email.setHtmlMsg("This is the message");
                email.send();
            } catch (EmailException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            Notification.show("Controlla l'indirizzo mail del destinatario");
        }
    });

    this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test);

}

From source file:dk.dma.ais.abnormal.analyzer.reports.ReportMailer.java

/**
 * Send email with subject and message body.
 * @param subject the email subject./*  w ww  .j a v a2s.  c  om*/
 * @param body the email body.
 */
public void send(String subject, String body) {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_HOST, "localhost"));
        email.setSmtpPort(configuration.getInt(CONFKEY_REPORTS_MAILER_SMTP_PORT, 465));
        email.setAuthenticator(
                new DefaultAuthenticator(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_USER, "anonymous"),
                        configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_PASS, "guest")));
        email.setStartTLSEnabled(false);
        email.setSSLOnConnect(configuration.getBoolean(CONFKEY_REPORTS_MAILER_SMTP_SSL, true));
        email.setFrom(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_FROM, ""));
        email.setSubject(subject);
        email.setHtmlMsg(body);
        String[] receivers = configuration.getStringArray(CONFKEY_REPORTS_MAILER_SMTP_TO);
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        email.send();
        LOG.info("Report sent with email to " + email.getToAddresses().toString() + " (\"" + subject + "\")");
    } catch (EmailException e) {
        LOG.error(e.getMessage(), e);
    }
}

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

/**
 * DOCUMENT ME!//from ww  w.  j av a  2  s.c  o  m
 *
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void sendIdentity(Session session, String repositoryName, String from, String to, String subject,
        String body) throws MailException {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(session);
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setHtmlMsg(body);
        email.setCharset(Charset.defaultCharset().displayName());

        email.send();
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
    }
}