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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

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  w w  .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.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());/*w  ww . j  a v a 2 s . co m*/
    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 {
        LOGGER.debug("Will contact SMTP server anonymously.");
    }
    email.setFrom(getSender(), session.getName());
    email.addTo(getRecipient());
    return email;
}

From source file:com.dattack.jtoolbox.commons.email.HtmlEmailBuilder.java

/**
 * Builder method.//  ww w  . j a  va 2  s  .c o m
 *
 * @return the HtmlEmail
 * @throws EmailException
 *             if an error occurs while creating the email
 */
public HtmlEmail build() throws EmailException {

    if (hostname == null || hostname.isEmpty()) {
        throw new EmailException(String.format("Invalid SMTP server (hostname: '%s')", hostname));
    }

    if (from == null || from.isEmpty()) {
        throw new EmailException(String.format("Invalid email address (FROM: '%s'", from));
    }

    final HtmlEmail email = new HtmlEmail();
    email.setHostName(hostname);
    email.setFrom(from);
    email.setSubject(subject);

    if (message != null && !message.isEmpty()) {
        email.setMsg(message);
    }

    if (port > 0) {
        email.setSmtpPort(port);
    }

    if (username != null && !username.isEmpty()) {
        email.setAuthenticator(new DefaultAuthenticator(username, password));
    }

    if (sslOnConnect != null) {
        email.setSSLOnConnect(sslOnConnect);
    }

    if (startTlsEnabled != null) {
        email.setStartTLSEnabled(startTlsEnabled);
    }

    if (!toList.isEmpty()) {
        email.setTo(toList);
    }

    if (!ccList.isEmpty()) {
        email.setCc(ccList);
    }

    if (!bccList.isEmpty()) {
        email.setBcc(bccList);
    }
    return email;
}

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

private void enviarEmailDBA() {
    try {/*ww w.  j  a  v  a 2  s  .  c o  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.ezequieljuliano.argos.util.SendMail.java

public void send() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(server.getHostName());
    email.setAuthentication(server.getUser(), server.getPassWord());
    email.setSSL(server.isSSL());//from w  w w. j  av a2  s .  c  om
    email.setSmtpPort(server.getPort());

    for (Involved involved : recipients) {
        email.addTo(involved.getEmail(), involved.getName());
    }

    email.setFrom(sender.getEmail(), sender.getName());
    email.setSubject(subject);
    email.setHtmlMsg(message);
    email.setCharset("UTF-8");

    EmailAttachment att;
    for (Attachment annex : attachment) {
        att = new EmailAttachment();
        att.setPath(annex.getPath());
        att.setDisposition(EmailAttachment.ATTACHMENT);
        att.setDescription(annex.getDescription());
        att.setName(annex.getName());
        email.attach(att);
    }

    email.send();
}

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 {//w ww.ja  va2  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:it.vige.greenarea.test.mail.SendMailTest.java

@Test
public void testSendMailToGoogle() throws Exception {
    HtmlEmail email = new HtmlEmail();
    try {//from  w  ww .j a  va2  s . c  o m
        email.setSubject("prova");
        email.setHtmlMsg("<div>ciao</div>");
        email.addTo("luca.stancapiano@vige.it");
        email.setSmtpPort(587);
        email.setHostName("smtp.gmail.com");
        email.setFrom("greenareavige@gmail.com");
        email.setAuthentication("greenareavige@gmail.com", "vulitgreenarea");
        email.setTLS(true);
        email.send();
    } catch (EmailException e) {
        fail();
    }

}

From source file:com.ning.metrics.meteo.publishers.AlertListener.java

private void createAndSendAlertEmail(String body) {
    try {/*from w ww. j  a v a2  s  . 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:io.marto.aem.utils.email.FreemarkerTemplatedMailerTest.java

private String getEmail(HtmlEmail htmlMail)
        throws EmailException, IOException, MessagingException, UnsupportedEncodingException {
    htmlMail.setHostName("localhost");
    htmlMail.buildMimeMessage();// w  ww .ja v  a  2  s  .c o m
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    htmlMail.getMimeMessage().writeTo(out);
    return out.toString("UTF-8");
}