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

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

Introduction

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

Prototype

public void setSmtpPort(final int aPortNumber) 

Source Link

Document

Set the port number of the outgoing mail server.

Usage

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

public void sendingHtml() {
    try {/*from  w w w .j  a v  a 2 s .com*/
        // 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("belchiorpalma@gmail.com", "Belchior Palma");
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject("Test email with inline image");
        email.setSubject(MimeUtility.encodeText("Test email with inline image", "UTF-8", "B"));

        // embed the image and get the content id
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo");

        // set the html message
        email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>");

        // 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);
    } catch (MalformedURLException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

/**
 * Send email./*ww  w  .  j a va 2s. com*/
 *
 * @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.github.robozonky.notifications.EmailHandler.java

private HtmlEmail createNewEmail(final SessionInfo session) throws EmailException {
    final HtmlEmail email = new HtmlEmail();
    email.setCharset(Defaults.CHARSET.displayName()); // otherwise the e-mail contents are mangled
    email.setHostName(getSmtpHostname());
    email.setSmtpPort(getSmtpPort());
    email.setStartTLSRequired(isStartTlsRequired());
    email.setSSLOnConnect(isSslOnConnectRequired());
    if (isAuthenticationRequired()) {
        final String username = getSmtpUsername();
        LOGGER.debug("Will contact SMTP server as '{}'.", username);
        email.setAuthentication(getSmtpUsername(), getSmtpPassword());
    } else {//from w  w w .  j av  a2s  .  c  o  m
        LOGGER.debug("Will contact SMTP server anonymously.");
    }
    email.setFrom(getSender(), session.getName());
    email.addTo(getRecipient());
    return email;
}

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

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {// w ww. ja v  a 2s.co 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//  w w w . j ava  2  s  .  c o  m
* @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:br.com.mysqlmonitor.monitor.Monitor.java

private void enviarEmailDBA() {
    try {//from   w w w  .java 2s.  co  m
        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.asisprojetos.email.SendEmail.java

public void enviar(String toEmail[], String subject, String templateFile, List<String> fileNames, String mes,
        int codContrato) {

    try {/*from w  w  w  .j a  v a 2  s  .c o m*/

        String htmlFileTemplate = loadHtmlFile(templateFile);

        for (String to : toEmail) {

            String htmlFile = htmlFileTemplate;

            // Create the email message
            HtmlEmail email = new HtmlEmail();
            email.setHostName(config.getHostname());
            email.setSmtpPort(config.getPort());
            email.setFrom(config.getFrom(), config.getFromName()); // remetente
            email.setAuthenticator(
                    new DefaultAuthenticator(config.getAuthenticatorUser(), config.getAuthenticatorPassword()));
            email.setSSL(true);
            email.setSubject(subject); //Assunto

            email.addTo(to);//para

            logger.debug("Enviando Email para : [{}] ", to);

            int i = 1;

            for (String fileName : fileNames) {

                String cid;

                if (fileName.startsWith("diagnostico")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph24$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de diagnostico nao encontrado.");
                    }
                } else if (fileName.startsWith("recorrencia")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph25$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de recorrencia nao encontrado.");
                    }
                } else {
                    cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                    htmlFile = StringUtils.replace(htmlFile, "$codGraph" + i + "$",
                            "<img src=\"cid:" + cid + "\">");
                    i++;
                }

            }

            //apaga $codGraph$ no usado do template
            for (int t = i; t <= 25; t++) {
                htmlFile = StringUtils.replace(htmlFile, "$codGraph" + t + "$", " ");
            }

            htmlFile = StringUtils.replace(htmlFile, "$MES$", mes);
            htmlFile = StringUtils.replace(htmlFile, "$MAIL$", to);
            htmlFile = StringUtils.replace(htmlFile, "$CONTRATO$", Integer.toString(codContrato));

            email.setHtmlMsg(htmlFile);

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

            // send the email
            email.send();

        }

        logger.debug("Email enviado com sucesso......");

    } catch (FileNotFoundException ex) {
        logger.error("Arquivo [{}/{}] nao encontrado para leitura.", config.getHtmlDirectory(), templateFile);
    } catch (Exception ex) {
        logger.error("Erro ao Enviar email : {}", ex);
    }

}

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   ww w .j  a  va  2s. c  om*/
    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:com.ning.metrics.meteo.publishers.AlertListener.java

private void createAndSendAlertEmail(String body) {
    try {/*from   w ww  . jav  a2s. com*/
        log.info(String.format("Sending alert email to [%s]: %s", config.getRecipients(), body));

        HtmlEmail email = new HtmlEmail();

        email.setTextMsg(body);
        email.setFrom("esper-is-awesome@example.com");
        email.setTo(Arrays.asList(new InternetAddress(config.getRecipients())));
        email.setHostName(config.getHost());
        email.setSmtpPort(config.getPort());
        email.send();
    } catch (Exception ex) {
        log.warn("Could not create or send email", ex);
    }
}

From source file:de.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java

public void send() throws EmailException {

    if (files != null && urls != null) {
        attachments = new EmailAttachment[files.length + urls.length];

        int cnt = 0;

        for (int i = 0; i < files.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setPath(files[i].getPath());
            attachments[cnt].setName(files[i].getName());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);

            cnt++;/* w w  w  .  j  av a 2s  .c  o  m*/
        }

        for (int i = 0; i < urls.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setURL(urls[i]);
            attachments[cnt].setName(urls[i].getFile());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);
            cnt++;
        }

    } else if (files != null) {
        attachments = new EmailAttachment[files.length];

        for (int i = 0; i < files.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setPath(files[i].getPath());
            attachments[i].setName(files[i].getName());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    } else if (urls != null) {
        attachments = new EmailAttachment[urls.length];

        for (int i = 0; i < urls.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setURL(urls[i]);
            attachments[i].setName(urls[i].getFile());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(Config.get("mailHost", ""));
    email.setSmtpPort(Config.getConfigInt("mailPort", 25));

    email.setTLS(Config.getConfigBoolean("mailTLS", false));
    email.setSSL(Config.getConfigBoolean("mailSSL", false));

    //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25));
    email.setAuthenticator(
            new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", "")));

    email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null));

    email.setSubject(subject);
    email.setHtmlMsg(body);
    email.setTextMsg(nohtmlmsg);

    for (int i = 0; i < adress.length; i++) {
        email.addTo(adress[i]);
    }

    if (cc != null) {
        for (int i = 0; i < cc.length; i++) {
            email.addCc(cc[i]);
        }
    }

    if (attachments != null) {
        for (int i = 0; i < attachments.length; i++) {
            email.attach(attachments[i]);
        }
    }

    email.send();

}