Example usage for org.apache.commons.mail Email setStartTLSEnabled

List of usage examples for org.apache.commons.mail Email setStartTLSEnabled

Introduction

In this page you can find the example usage for org.apache.commons.mail Email setStartTLSEnabled.

Prototype

public Email setStartTLSEnabled(final boolean startTlsEnabled) 

Source Link

Document

Set or disable the STARTTLS encryption.

Usage

From source file:org.openhab.binding.mail.internal.SMTPHandler.java

/**
 * use this server to send a mail//from   ww w .j  av  a  2  s  .  c  om
 *
 * @param mail the Email that needs to be sent
 * @return true if successful, false if failed
 */
public boolean sendMail(Email mail) {
    try {
        if (mail.getFromAddress() == null) {
            mail.setFrom(config.sender);
        }
        mail.setHostName(config.hostname);
        switch (config.security) {
        case SSL:
            mail.setSSLOnConnect(true);
            mail.setSslSmtpPort(config.port.toString());
            break;
        case TLS:
            mail.setStartTLSEnabled(true);
            mail.setStartTLSRequired(true);
            mail.setSmtpPort(config.port);
            break;
        case PLAIN:
            mail.setSmtpPort(config.port);
        }
        if (!config.username.isEmpty() && !config.password.isEmpty()) {
            mail.setAuthenticator(new DefaultAuthenticator(config.username, config.password));
        }
        mail.send();
    } catch (EmailException e) {
        logger.warn("Trying to send mail but exception occured: {} ", e.getMessage());
        return false;
    }
    return true;
}

From source file:org.paxml.bean.EmailTag.java

private Email createEmail(Collection<String> to, Collection<String> cc, Collection<String> bcc)
        throws EmailException {
    Email email;
    if (attachment == null || attachment.isEmpty()) {
        email = new SimpleEmail();
    } else {/*  ww  w . j ava 2  s .c o  m*/
        MultiPartEmail mpemail = new MultiPartEmail();
        for (Object att : attachment) {
            mpemail.attach(makeAttachment(att.toString()));
        }
        email = mpemail;
    }

    if (StringUtils.isNotEmpty(username)) {
        String pwd = null;
        if (password instanceof Secret) {
            pwd = ((Secret) password).getDecrypted();
        } else if (password != null) {
            pwd = password.toString();
        }
        email.setAuthenticator(new DefaultAuthenticator(username, pwd));
    }

    email.setHostName(findHost());
    email.setSSLOnConnect(ssl);
    if (port > 0) {
        if (ssl) {
            email.setSslSmtpPort(port + "");
        } else {
            email.setSmtpPort(port);
        }
    }
    if (replyTo != null) {
        for (Object r : replyTo) {
            email.addReplyTo(r.toString());
        }
    }
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(text);
    if (to != null) {
        for (String r : to) {
            email.addTo(r);
        }
    }
    if (cc != null) {
        for (String r : cc) {
            email.addCc(r);
        }
    }
    if (bcc != null) {
        for (String r : bcc) {
            email.addBcc(r);
        }
    }
    email.setSSLCheckServerIdentity(sslCheckServerIdentity);
    email.setStartTLSEnabled(tls);
    email.setStartTLSRequired(tls);
    return email;
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

/**
 * Apply server configuration to email.//from  www .j a v  a  2 s . c om
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}

From source file:org.structr.common.MailHelper.java

private static void setup(final Email mail, final String to, final String toName, final String from,
        final String fromName, final String cc, final String bcc, final String bounce, final String subject)
        throws EmailException {

    // FIXME: this might be slow if the config file is read each time
    final Properties config = Services.getInstance().getCurrentConfig();
    final String smtpHost = config.getProperty(Services.SMTP_HOST, "localhost");
    final String smtpPort = config.getProperty(Services.SMTP_PORT, "25");
    final String smtpUser = config.getProperty(Services.SMTP_USER);
    final String smtpPassword = config.getProperty(Services.SMTP_PASSWORD);
    final String smtpUseTLS = config.getProperty(Services.SMTP_USE_TLS, "true");
    final String smtpRequireTLS = config.getProperty(Services.SMTP_REQUIRE_TLS, "false");

    mail.setCharset(charset);/*from   www  . j  a va  2s.  co  m*/
    mail.setHostName(smtpHost);
    mail.setSmtpPort(Integer.parseInt(smtpPort));
    mail.setStartTLSEnabled(Boolean.parseBoolean(smtpUseTLS));
    mail.setStartTLSRequired(Boolean.parseBoolean(smtpRequireTLS));
    mail.setCharset(charset);
    mail.setHostName(smtpHost);
    mail.setSmtpPort(Integer.parseInt(smtpPort));

    if (StringUtils.isNotBlank(smtpUser) && StringUtils.isNotBlank(smtpPassword)) {
        mail.setAuthentication(smtpUser, smtpPassword);
    }

    mail.addTo(to, toName);
    mail.setFrom(from, fromName);

    if (StringUtils.isNotBlank(cc)) {
        mail.addCc(cc);
    }

    if (StringUtils.isNotBlank(bcc)) {
        mail.addBcc(bcc);
    }

    if (StringUtils.isNotBlank(bounce)) {
        mail.setBounceAddress(bounce);
    }

    mail.setSubject(subject);

}

From source file:paquetes.AlertSchedule.java

@Schedule(hour = "8", dayOfWeek = "*", info = "Todos los dias a las 8:00 a.m.")
//@Schedule(second = "*", minute = "*/10", hour = "*", persistent= true, info = "cada 10 minutos")

public void performTask() throws EmailException {

    long timeInit = System.currentTimeMillis();
    ConfiguracionMail();/* ww w .  jav a  2s  . c om*/

    log.info(":. Inicio TareaProgramada cada dia");

    try {
        timeInit = System.currentTimeMillis();

        obtenerAlertas();

        // Luego de obtener las alertas las recorremos para conformar cada uno de los selects de validacion
        alertas.stream().forEach((ale) -> {

            id_ale = ale.getId_ale();
            llenarAlertasUsuarios(ale.getId_ale());
            verificarPorTipoAlerta(ale);
            nom_tip_ale = ale.getNom_tip_ale();

            logale.stream().forEach((lgal) -> {

                try {
                    Email email = new SimpleEmail();
                    email.setHostName(this.hostname);
                    email.setSmtpPort(Integer.parseInt(this.smtp_port));
                    email.setAuthenticator(new DefaultAuthenticator(this.user, this.pass));
                    // TLS agregado para server AWS Se quita comentario a setSSL.
                    email.setStartTLSEnabled(true);
                    email.setStartTLSRequired(true);

                    // Comentariado para funcionar con Gmail
                    //email.setSSLOnConnect(true);

                    email.setFrom(this.remitente);
                    email.setSubject(nom_tip_ale);
                    email.setMsg(lgal.getAle_des());

                    alertasusuarios.stream().forEach((mailDestino) -> {
                        try {
                            email.addTo(mailDestino.getMailusu());
                        } catch (Exception e) {
                            System.out.println("Error en la obtencion de destinatarios. " + e.getMessage());
                        }
                    });

                    email.send();
                } catch (Exception e) {
                    System.out.println("Error en la conformacion del correo. " + e.getMessage());
                }
            });
        });
    } catch (Exception e) {
        log.error("Error en la tarea programada");
        log.info(e);
    }

    long time = System.currentTimeMillis();
    time = System.currentTimeMillis() - timeInit;
    log.info(":. Fin tarea programada. Tiempo de proceso = " + time);

}

From source file:scouter.plugin.server.alert.email.EmailPlugin.java

/**
 * ? ? ??  <br>/* w w w. j  a v  a  2  s . c o m*/
 *   ? ?? ?? <br>
 * @param pack ?? ?   pack
 */
@ServerPlugin(PluginConstants.PLUGIN_SERVER_ALERT)
public void alert(final AlertPack pack) {
    /* Email    */
    if (conf.getBoolean("ext_plugin_email_send_alert", true)) {

        /* 
         * Get log level (0 : INFO, 1 : WARN, 2 : ERROR, 3 : FATAL)
         * 0   ??  ??  ?.
         */
        int level = conf.getInt("ext_plugin_email_level", 0);

        /* ?  level   ? ? ?  */
        if (level <= pack.level) {
            new Thread() {
                public void run() {
                    try {

                        // Get server configurations for email
                        String hostname = conf.getValue("ext_plugin_email_smtp_hostname", "smtp.gmail.com"); // smtp 
                        int port = conf.getInt("ext_plugin_email_smtp_port", 587); // smtp ?

                        String username = conf.getValue("ext_plugin_email_username", "haniumscouter@gmail.com"); // ? ?? 
                        String password = conf.getValue("ext_plugin_email_password", "dkqorhvk!@#$"); // ? ?? 

                        boolean tlsEnabled = conf.getBoolean("ext_plugin_email_tls_enabled", true); // tls (gamil? true)

                        String from = conf.getValue("ext_plugin_email_from_address", "haniumscouter@gmail.com"); // ?? ? ?? 
                        String to = conf.getValue("ext_plugin_email_to_address", "occidere@naver.com"); // ? ??(? , )
                        String cc = conf.getValue("ext_plugin_email_cc_address"); // cc ??

                        assert hostname != null;
                        assert port > 0;
                        assert username != null;
                        assert password != null;
                        assert from != null;
                        assert to != null;

                        // Get agent Name.  ??.
                        String name = AgentManager.getAgentName(pack.objHash) == null ? "N/A"
                                : AgentManager.getAgentName(pack.objHash);

                        if (name.equals("N/A") && pack.message.endsWith("connected.")) {
                            int idx = pack.message.indexOf("connected");
                            if (pack.message.indexOf("reconnected") > -1)
                                name = pack.message.substring(0, idx - 6);
                            else
                                name = pack.message.substring(0, idx - 4);
                        }

                        // Make email subject
                        String subject = "[" + AlertLevel.getName(pack.level) + "] "
                                + pack.objType.toUpperCase() + "(" + name + ") : " + pack.title;

                        String title = pack.title;
                        String msg = pack.message;

                        /* 
                         * Agent ? (inactivate) ? ? .
                         * ?  ,  ? ? Agent  ?  ?
                         * Agent ?  title? ?    .
                         */
                        if (title.equals("INACTIVE_OBJECT")) {
                            title = name + "  (Inactivated) ?!";
                            msg = pack.message.substring(0, pack.message.indexOf("OBJECT") - 1);
                        }

                        //? ? ? ?  ?
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd? HH mm ss");

                        // Make email message
                        String message = "[??   ?   ver.20170815]"
                                + Util.NEW_LINE + "[ ] : " + title + Util.NEW_LINE + "[ ] : "
                                + sdf.format(new Date(pack.time)) + Util.NEW_LINE + "[ ] : "
                                + pack.objType.toUpperCase() + Util.NEW_LINE + "[? ] : " + name
                                + Util.NEW_LINE + "[ ] : " + AlertLevel.getName(pack.level)
                                + Util.NEW_LINE + "[ ] : " + msg + Util.NEW_LINE;

                        // Create an Email instance
                        Email email = new SimpleEmail();

                        email.setHostName(hostname);
                        email.setSmtpPort(port);
                        email.setAuthenticator(new DefaultAuthenticator(username, password));
                        email.setStartTLSEnabled(tlsEnabled);
                        email.setFrom(from);
                        email.setSubject(subject);
                        email.setMsg(message);

                        //? ,   
                        for (String addr : to.split(",")) {
                            email.addTo(addr);
                        }

                        //cc  ,   
                        if (cc != null) {
                            for (String addr : cc.split(","))
                                email.addCc(addr);
                        }

                        // Send the email
                        email.send();

                        println("Email about " + name + " sent to [" + to + "] successfully.");
                        Logger.println("Email about " + name + " sent to [" + to + "] successfully.");
                    } catch (Exception e) {
                        println("[? ] : " + e.getMessage());
                        Logger.printStackTrace(e);

                        if (conf._trace) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }
}