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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

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  .  j av  a  2  s.com
        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:de.knurt.fam.core.util.mail.UserMailSender.java

private static boolean send(UserMail um) {
    boolean sendSucc = false;
    UserMailSender dse = getInstance();/* www.  ja v a2 s .com*/
    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:model.Email.java

public static void sendToken(String receiver, String token) throws EmailException {

    SimpleEmail email = new SimpleEmail();
    String message = "Para sua segurana, voc precisa colocar o cdigo abaixo para continar a transao.\n";
    message += "Token: " + token + "\n";
    message += "\nO sistema de token  para sua segurana, sempre ao realizar uma transao, um novo token  gerado ";
    message += " e enviado  voc.";

    try {/* w w w.j a v  a2 s . c  o  m*/
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("totheworldgroup@gmail.com", "albrcalu"));
        email.setSSLOnConnect(true);
        email.setFrom("totheworldgroup@gmail.com");
        email.setSubject("Token para realizar transao");
        email.setMsg(message);
        email.addTo(receiver);
        email.send();

    } catch (EmailException e) {
        System.out.println(e.getMessage());
    }

}

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);
    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);/* w ww.ja v  a2 s  .  c om*/
    }
    email.setFrom(gmail_username + "@gmail.com", gmail_username);

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

}

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.ja  v a 2 s . com*/
 *    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.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) {
        //???//from  w  ww  .ja va  2s .  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:model.Email.java

public static void sendConfirmation(String receiver, String token, PersonalAccount account)
        throws EmailException {

    SimpleEmail email = new SimpleEmail();
    String message = "Sua conta foi criada com sucesso, porm ainda est inativa.\n";
    message += "Nmero da conta: " + account.getNumber() + "\n";
    message += "Agncia: " + account.getAgency().getNumber() + "\n";
    message += "Token de autentificao: " + token + "\n";
    message += "Com este token voc  capaz de definir uma senha para sua conta para, ento, utiliz-la.\n";
    message += "\nCaso voc perca este token, entre novamente com as informaes para abrir conta,";
    message += " e um novo token ser gerado e reenviado  voc.";

    try {// ww w.j  av  a2  s. c  o  m
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("totheworldgroup@gmail.com", "albrcalu"));
        email.setSSLOnConnect(true);
        email.setFrom("totheworldgroup@gmail.com");
        email.setSubject("Token de autentificao");
        email.setMsg(message);
        email.addTo(receiver);
        email.send();

    } catch (EmailException e) {
        System.out.println(e.getMessage());
    }

}

From source file:funcoes.funcoes.java

public static void enviardEmailSimpes(String emailPara, String nomePara, String assunto, String mensagem)
        throws EmailException {

    SimpleEmail email = new SimpleEmail();
    //Utilize o hostname do seu provedor de email
    //System.out.println("alterando hostname...");

    email.setHostName("smtp.gmail.com");
    //Quando a porta utilizada no  a padro (gmail = 465)
    email.setSmtpPort(465);/*from   w  w w  .j  a  va2  s  . c  om*/
    //Adicione os destinatrios
    email.addTo(emailPara, nomePara);
    //Configure o seu email do qual enviar
    email.setFrom("cbjsolutions@gmail.com", "CBJ Solutions");
    //Adicione um assunto
    email.setSubject(assunto);
    //Adicione a mensagem do email
    email.setMsg(mensagem);
    //Para autenticar no servidor  necessrio chamar os dois mtodos abaixo
    //System.out.println("autenticando...");
    email.setSSL(true);
    email.setAuthentication("cbjsolutions", "slipclown");
    //System.out.println("enviando...");
    email.send();
    //System.out.println("Email enviado!");

}

From source file:dk.clarin.tools.workflow.java

public static void sendMail(int status, String name, String string1, String toolErrorMessage,
        String toolsandfiles, String mail2) throws org.apache.commons.mail.EmailException {
    try {//from   w w  w.  j  a va  2 s.c o m
        logger.debug("sendMail(" + status + ", " + name + ", ... , ... , " + mail2 + ")");

        SimpleEmail email = new SimpleEmail();
        email.setHostName(ToolsProperties.mailServer);
        email.setFrom(ToolsProperties.mailFrom, ToolsProperties.mailFromName);
        email.setSmtpPort(Integer.parseInt(ToolsProperties.mailPort));
        email.setCharset("UTF-8");

        String body = "some body";
        String subject = "some subject ";
        switch (status) {
        case ACCEPT:
            subject = "[clarin.dk] Ny data fra integrerede vrktjer";
            body = "<html><body><p>"
                    + "Vi har modtaget dit nske om at oprette ny data ved hjlp af integrerede vrktjer.<br /><br />\n\n"
                    + "Nr oprettelsen er frdig, vil du modtage en email igen, der bekrfter at "
                    + "oprettelsen gik godt, samt en liste over URL'er hvor du vil kunne finde dine data<br /><br />\n\n"
                    + "Du kan ikke svare p denne email. Hvis ovenstende oplysninger ikke er rigtige, "
                    + "eller du har sprgsml, kan du henvende dig p mail-adressen admin@clarin.dk<br /><br />\n\n"
                    + "Venlig hilsen \nclarin.dk</p></body></html>";
            break;
        case WRAPUP:
            logger.debug("sendMail(" + status + ", " + name + ", " + string1 + ", " + toolErrorMessage + ", "
                    + toolsandfiles + ", " + mail2 + ")");
            subject = "[clarin.dk]  Samlet output fra integrerede vrktjer - success";
            body = "<html><body><p>"
                    + "Vi har modtaget dit nske om at oprette ny data ved hjlp af integrerede vrktjer.<br />\n\n"
                    + "Du kan se resultaterne her:<br /><br />\n\n";

            body += "<a href=\"" + string1 + "?JobNr=" + toolsandfiles + "\">resultater</a>";
            body += "\n\n<br /><br />Bemrk!<br />\n"
                    + "1) Hvert resultat kan hentes n gang, hvorefter resultatet straks slettes fra serveren.<br />\n"
                    + "2) Under alle omstndigheder slettes ikke-hentede resultaterne efter et par dage.<br /><br />\n\n"
                    + "Du kan ikke svare p denne email. Hvis ovenstende oplysninger ikke er rigtige, "
                    + "eller du har sprgsml, kan du henvende dig p mail-adressen admin@clarin.dk<br /><br />\n\n"
                    + "Venlig hilsen \nclarin.dk</p></body></html>";
            break;
        case ERRORUSER:
            subject = "[clarin.dk] Integreret vrktj melder fejl";
            body = "<html><body><p>" + string1 + (toolErrorMessage.equals("") ? ""
                    : "<br /><br />\n\nClarin.dk har modtaget denne besked fra vrktjet:<br /><br />\n\n"
                            + toolErrorMessage)
                    + "<br /><br />\n\n" + errorInfo(toolsandfiles)
                    + "<br /><br />\n\nDu kan ikke svare p denne email. Fejlbeskeden er ogs sendt til systemadministratoren."
                    + "<br /><br />\n\nVenlig hilsen\nclarin.dk</p></body></html>";
            break;
        default: //ERROR
            subject = "[clarin.dk] Integreret vrktj melder fejl";
            body = "<html><body><p>" + string1 + (toolErrorMessage.equals("") ? ""
                    : "<br /><br />\n\nClarin.dk har modtaget denne besked fra vrktjet:<br /><br />\n\n"
                            + toolErrorMessage)
                    + "<br /><br />\n\n" + errorInfo(toolsandfiles)
                    + "<br /><br />\n\nVenlig hilsen\nclarin.dk</p></body></html>";
            break;
        }
        email.setSubject(subject);
        email.setMsg(body);
        email.updateContentType("text/html; charset=UTF-8");
        email.addTo(mail2, name);
        email.send();
    } catch (org.apache.commons.mail.EmailException m) {
        logger.error("[Tools generated org.apache.commons.mail.EmailException] mailServer:"
                + ToolsProperties.mailServer + ", mailFrom:" + ToolsProperties.mailFrom + ", mailFromName:"
                + ToolsProperties.mailFromName + ", mailPort:" + Integer.parseInt(ToolsProperties.mailPort)
                + ", mail2:" + mail2 + ", name:" + name);
        //m.printStackTrace();
        logger.error("{} Error sending email. Message is: {}", "Tools", m.getMessage());
    } catch (Exception e) {//Catch exception if any
        logger.error("[Tools generated Exception] mailServer:" + ToolsProperties.mailServer + ", mailFrom:"
                + ToolsProperties.mailFrom + ", mailFromName:" + ToolsProperties.mailFromName + ", mailPort:"
                + Integer.parseInt(ToolsProperties.mailPort) + ", mail2:" + mail2 + ", name:" + name);
        logger.error("{} Exception:{}", "Tools", e.getMessage());
    }
}

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 {//from   w w w  . j ava  2 s.co 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;
}