Example usage for org.apache.commons.mail SimpleEmail setAuthentication

List of usage examples for org.apache.commons.mail SimpleEmail setAuthentication

Introduction

In this page you can find the example usage for org.apache.commons.mail SimpleEmail setAuthentication.

Prototype

public void setAuthentication(final String userName, final String password) 

Source Link

Document

Sets the userName and password if authentication is needed.

Usage

From source file:com.mycompany.webtestegit.util.TesteMail.java

public static void main(String[] args) {
    SimpleEmail email = new SimpleEmail();
    email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail 
    try {//from w  w w.  ja  v a2  s  .c o m
        email.addTo("cfs.bsi@gmail.com", "Christian"); //destinatrio 
        email.setFrom("programacao.micromap@gmail.com", "Micromap"); // remetente 
        email.setSubject("Titulo do e-mail"); // assunto do e-mail 
        email.setMsg("Teste de Email utilizando commons-email"); //conteudo do e-mail 
        email.setAuthentication("ORIGEM", "SENHA");
        email.setSSLCheckServerIdentity(true);
        email.send(); //envia o e-mail
    } catch (EmailException ex) {
        Logger.getLogger(TesteMail.class.getName()).log(Level.SEVERE, null, ex);
    }

    //EMAIL HTML
    //        HtmlEmail email = new HtmlEmail();
    //
    //        try {
    //            email.setHostName("smtp.gmail.com");
    //            email.addTo("cfs.bsi@gmail.com", "Cfs");
    //            email.setFrom("programacao.micromap@gmail.com", "Micromap"); 
    //            email.setSubject("Teste de e-mail em formato HTML");   
    //
    //
    //            // adiciona uma imagem ao corpo da mensagem e retorna seu id 
    //            URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
    //            String cid = email.embed(url, "Apache logo");   
    //
    //            // configura a mensagem para o formato HTML 
    //            email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>");   
    //
    //            // configure uma mensagem alternativa caso o servidor no suporte HTML 
    //            email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");   
    //            email.setAuthentication("ORIGEM", "SENHA");
    //            
    //            // envia o e-mail 
    //            email.send();
    //        } catch (EmailException ex) {
    //            Logger.getLogger(TesteMail.class.getName()).log(Level.SEVERE, null, ex);
    //        } catch (MalformedURLException ex) {
    //            Logger.getLogger(TesteMail.class.getName()).log(Level.SEVERE, null, ex);
    //        }
}

From source file:edu.du.penrose.systems.util.SendMail.java

/**
 * NOTE VERY WELL!! The sends an ssl email, when used with Fedora libraries this throws a SSL Exception, in order to fix this
 * The following SSL system properties are cleared and then restored after the email is sent. l...<br>
 * /*from w w  w  .  j av a2  s . c  o  m*/
 *    System.clearProperty( "javax.net.ssl.keyStore" );
 *  System.clearProperty( "javax.net.ssl.keyStorePassword" );
 *  System.clearProperty( "javax.net.ssl.keyStoreType" );
 *  System.clearProperty( "javax.net.ssl.trustStore" );
 *  System.clearProperty( "javax.net.ssl.trustStorePassword" );
 *  System.clearProperty( "javax.net.ssl.trustStoreType" );
 *  
 * @param recipients
 * @param subject
 * @param message
 * @param from
 * @param smptServerHost
 * @param smtpUser
 * @param smtpPassword
 * @param port
 * @param sslEmail
 */
public static void postMailWithAuthenication(String recipients[], String subject, String message, String from,
        String smptServerHost, String smtpUser, String smtpPassword, String port, boolean sslEmail) {
    if (from == null || !from.contains("@")) {
        logger.info("Unable to send email, missing from address.");
        return;
    }

    String user = smtpUser.trim();
    String password = smtpPassword.trim();

    int numberOfValidRecipients = 0;
    for (int i = 0; i < recipients.length; i++) {
        if (recipients[i] != null && recipients[i].length() > 0 && recipients[i].contains("@")) {
            numberOfValidRecipients++;
        }
    }

    if (numberOfValidRecipients == 0) {
        logger.info("Unable to send email, missing recipients address.");
        return;
    }

    SimpleEmail email = new SimpleEmail();
    email.setSSL(sslEmail);
    email.setSmtpPort(Integer.valueOf(port));
    email.setAuthentication(user, password);
    email.setHostName(smptServerHost);

    try {
        for (int i = 0; i < numberOfValidRecipients; i++) {
            email.addTo(recipients[i]);
        }
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(message);

        //   System.setProperty( "javax.net.debug", "ssl" );

        String keyStore = System.getProperty("javax.net.ssl.keyStore");
        String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");

        System.clearProperty("javax.net.ssl.keyStore");
        System.clearProperty("javax.net.ssl.keyStorePassword");
        System.clearProperty("javax.net.ssl.keyStoreType");
        System.clearProperty("javax.net.ssl.trustStore");
        System.clearProperty("javax.net.ssl.trustStorePassword");
        System.clearProperty("javax.net.ssl.trustStoreType");

        email.send();

        System.setProperty("javax.net.ssl.keyStore", keyStore);
        System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
        System.setProperty("javax.net.ssl.keyStoreType", keyStoreType);
        System.setProperty("javax.net.ssl.trustStore", trustStore);
        System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
        System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);

    } catch (Exception e) {
        logger.error("ERROR sending email:" + e.getLocalizedMessage());
    }

}

From source file:com.bc.appbase.ui.dialog.SendReportAction.java

private static Email getEmail(String host, int port, String emailAddress, String password, String subject) {

    final SimpleEmail email = new SimpleEmail();

    try {//w  w  w . j a v  a 2s . c o  m
        email.addTo(emailAddress);
    } catch (EmailException e) {
        logger.log(Level.WARNING,
                "Error add `to address`: " + emailAddress + " to email with subject: " + subject, e);
        return null;
    }

    if (password != null) {
        email.setAuthentication(emailAddress, password);
    }
    email.setDebug(logger.isLoggable(Level.FINE));

    try {
        email.setFrom(emailAddress);
    } catch (EmailException e) {
        logger.log(Level.WARNING,
                "Error setting `from address` = " + emailAddress + " to email with subject: " + subject, e);
        return null;
    }

    email.setHostName(host);
    email.setSmtpPort(port);

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

    email.setSubject(subject);

    return email;
}

From source file:de.knurt.fam.core.util.mail.UserMailSender.java

private static boolean send(UserMail um) {
    boolean sendSucc = false;
    UserMailSender dse = getInstance();/* ww w  . ja v a  2 s .co  m*/
    if (um.hasBeenSent() == false) {
        if (um.mustBeSendNow()) {
            // prepare
            SimpleEmail email = new SimpleEmail();
            email.setHostName(dse.hostName);
            email.setSmtpPort(dse.smtpPort);
            // mail server using pass
            if (dse.authName != null) {
                email.setAuthentication(dse.authName, dse.authPass);
            }
            Map<String, String> headers = new Hashtable<String, String>();
            // headers.put("Subject", um.getSubject());
            email.setSubject(um.getSubject());
            headers.put("Content-Type", "text/plain; charset=utf-8");
            headers.put("Content-Transfer-Encoding", "base64");
            email.setHeaders(headers);
            boolean creatingSucc = false;
            try {
                email.addTo(um.getTo(), um.getUsername());
                email.setFrom(dse.fromMail, dse.fromName);
                email.setMsg(um.getMsg());
                creatingSucc = true;
            } catch (EmailException ex) {
                FamLog.logException(UserMailSender.class, ex,
                        "creating mail failed::" + um.getTo() + "::" + um.getUsername() + "::" + um.getId(),
                        200904031116l);
            }

            if (creatingSucc && FamConnector.isDev() == false) {
                try {
                    email.send();
                    sendSucc = true;
                } catch (EmailException ex) {
                    FamLog.exception("sending a mail failed: " + ex.getMessage() + "-" + dse.fromMail + "-"
                            + dse.fromName, ex, 200904031018l);
                }
            } else { // just dev mode - do not send any mails
                sendSucc = true;
            }
        }
    } else {
        FamLog.logException(UserMailSender.class,
                new DataIntegrityViolationException("try to send a mail twice"), "try to send a mail twice",
                200908201836l);
    }
    return sendSucc;
}

From source file:gsn.utils.GSNMonitor.java

private static void sendMail() throws EmailException {

    SimpleEmail email = new SimpleEmail();
    //email.setDebug(true);
    email.setHostName(SMTP_GMAIL_COM);/*  w  ww .j a  va2s .  c  o m*/
    email.setAuthentication(gmail_username, gmail_password);
    //System.out.println(gmail_username +" "+ gmail_password);
    email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
    email.getMailSession().getProperties().put("mail.smtp.auth", "true");
    email.getMailSession().getProperties().put("mail.debug", "true");
    email.getMailSession().getProperties().put("mail.smtp.port", "465");
    email.getMailSession().getProperties().put("mail.smtp.socketFactory.port", "465");
    email.getMailSession().getProperties().put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    email.getMailSession().getProperties().put("mail.smtp.socketFactory.fallback", "false");
    email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");

    for (String s : listOfMails) {
        email.addTo(s);
    }
    email.setFrom(gmail_username + "@gmail.com", gmail_username);

    email.setSubject("[GSN Alert] " + summary.toString());
    email.setMsg(report.toString());
    email.send();

}

From source file:com.kamike.misc.MailUtils.java

public static void sendSystemMail(String email, String msg) {
    SimpleEmail mail = new SimpleEmail();
    if (SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_SMTP) == null
            && SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL) == null
            && SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_ACCOUNT) == null
            && SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_PASSWORD) == null) {
        //???//w  w  w.  j  av a2 s . c o m
        return;
    }
    try {
        mail.setHostName(SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_SMTP));
        mail.addTo(email, email);
        mail.setFrom(SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL), "?");
        mail.setAuthentication(SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_ACCOUNT),
                SystemConfig.getInstance().getParameter(SystemParam.SYSTEM_EMAIL_PASSWORD));
        mail.setSubject("??");
        mail.setMsg(msg);
        String a = mail.send();
        System.out.println(a);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:br.com.gamestore.controler.ChamadoControler.java

/**
 * ENVIA EMAIL PARA O USU?RIO, RESPONDENDO O CHAMADO MESMO
 * @param email//from  www. j  ava2 s  . c o  m
 * @param comentario
 * @throws EmailException 
 */
public void enviarEmailChamdo(String email, String comentario) throws EmailException {

    //String emailusuario = request.getParameter("email");
    SimpleEmail simpleemail = new SimpleEmail();
    simpleemail.setHostName("smtp.gmail.com");
    simpleemail.setSmtpPort(465);
    simpleemail.setAuthentication("rkfsystem@gmail.com", "rkfsystemgamestore");
    simpleemail.setSSLOnConnect(true);
    simpleemail.setFrom("rkfsystem@gmail.com");
    simpleemail.setSubject("RESPOST DO CHAMADO");
    simpleemail.setMsg(comentario);
    simpleemail.addTo(email);
    simpleemail.send();

}

From source file:br.com.gamestore.controler.UsuarioControler.java

/**
 * ENVIA O EMAIL COM A SENHA DO USU?RIO, QUANDO O MESMO FOR CRIADO
 * @param senha//from   ww  w .ja  va 2s .  co m
 * @param emailusuario
 * @throws EmailException 
 */
public void enviarEmail(String senha, String emailusuario) throws EmailException {

    //String emailusuario = request.getParameter("email");
    SimpleEmail email = new SimpleEmail();
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(465);
    email.setAuthentication("rkfsystem@gmail.com", "rkfsystemgamestore");
    email.setSSLOnConnect(true);
    email.setFrom("rkfsystem@gmail.com");
    email.setSubject("senha de acesso ao sistema");
    email.setMsg("Senha: " + senha.replaceAll("-", "").substring(0, 5));
    email.addTo(emailusuario);
    email.send();

}

From source file:br.vn.Model.Filtros.Email.java

public void envia(String emailcliente) {

    try {// w ww  .  jav  a  2  s .  c  o m
        SimpleEmail email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthentication("Kleriston.firmino@gmail.com", "cavalo15");
        email.setSSLOnConnect(true);
        email.setFrom("teste.ads@gmail.com");
        email.setSubject("Recuperar Senha");
        email.setMsg(
                " [url=\"www.google.com.br\"][img]https://www.google.com.br/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwig17C98bnOAhVClZAKHTIqCEkQjRwIBw&url=http%3A%2F%2Fwww.gigabytetls.com%2F%23!servicos%2Fcjg9&psig=AFQjCNFe4nf3QiYJl9hhHxXmvVESfqvE4g&ust=1471022895224204[/img][/url]");
        email.addTo(emailcliente);
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:br.vn.Controlador.RecuperaSenhaBean.java

public String envia(String emailCliente) {

    c = repCliente.recuperaEmail();/*from w w  w .ja v  a 2 s.  c  om*/
    for (int i = 0; i < c.size(); i++) {
        if (c.get(i).getEmail().equals(emailCliente)) {

            try {
                SimpleEmail email = new SimpleEmail();
                email.setHostName("smtp.googlemail.com");
                email.setSmtpPort(465);
                email.setAuthentication("Kleriston.firmino@gmail.com", "cavalo15");
                email.setSSLOnConnect(true);
                email.setFrom("teste.ads@gmail.com");
                email.setSubject("Recuperar Senha");
                email.setMsg("Ateno: " + c.get(i).getNome() + " Para Recuperar Sua Senha Click Aqui ===>"
                        + "http://localhost:8084/Restaurante/faces/faces/RecuperarSenha.xhtml");
                email.addTo(emailCliente);

                email.send();
            } catch (EmailException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ateno! "
                    + " Em Instantes Voc Receber Um Email Com as Instrues Para Recuperar Sua Senha!"));
            return "/index.xhtml";
        }

    }
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ateno! " + " Email Incorreto!"));
    return "/EnviarEmail.xhtml";
}