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

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

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail 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.smi.travel.controller.mail.SendMail.java

public static void main(String args[]) throws Exception {
    EmailAttachment attachment = new EmailAttachment();
    HtmlEmail email = new HtmlEmail();
    try {//from   w ww  .j a  va2s .c  om
        //            attachment.setPath("C:\\Users\\chonnasith\\Desktop\\test.txt");
        //            attachment.setDescription("file attachment");
        //            attachment.setName("test.txt");
        //            email.attach(attachment);
        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setAuthentication(username, password);
        email.setSSLOnConnect(true);
        //            email.setStartTLSEnabled(true);
        //            email.setStartTLSRequired(true);
        email.setFrom(username);
        email.setSubject(subject);
        email.addTo(addto);
        email.setHtmlMsg(message);
        email.send();
        System.out.println("Email Send");
        System.out.println("Port : " + email.getSmtpPort());
    } catch (EmailException ex) {
        System.out.println("Email Exception");
        System.out.println("Port : " + email.getSmtpPort());
        ex.printStackTrace();
    }

    //        InetAddress host = InetAddress.getByName("mail.foobar.com");
    //        System.out.println("host.isReachable(1000) = " + host.isReachable(1000));

    //        int port = 587;
    //        String host = "smtp.gmail.com";
    //        String user = "username@gmail.com";
    //        String pwd = "email password";
    //
    //        try {
    //            Properties props = new Properties();
    //            // required for gmail 
    //            props.put("mail.smtp.starttls.enable","true");
    //            props.put("mail.smtp.auth", "true");
    //            // or use getDefaultInstance instance if desired...
    //            Session session = Session.getInstance(props, null);
    //            Transport transport = session.getTransport("smtp");
    //            transport.connect(host, port, user, pwd);
    //            transport.close();
    //            System.out.println("success");
    //         } 
    //         catch(AuthenticationFailedException e) {
    //               System.out.println("AuthenticationFailedException - for authentication failures");
    //               e.printStackTrace();
    //         }
    //         catch(MessagingException e) {
    //               System.out.println("for other failures");
    //               e.printStackTrace();
    //         }

    //        Properties prop=new Properties();
    //        prop.put("mail.smtp.auth", "true");
    //        prop.put("mail.smtp.host", "smtp.gmail.com");
    //        prop.put("mail.smtp.port", "587");
    //        prop.put("mail.smtp.starttls.enable", "true");
    //
    //        Session session = Session.getDefaultInstance(prop,
    //        new javax.mail.Authenticator() {
    //            protected PasswordAuthentication getPasswordAuthentication() {
    //                return new PasswordAuthentication("finance@wendytour", "wendytr");
    //          }
    //        });
    //        
    //        try {
    //            String body="Dear Renish Khunt Welcome";
    //            String htmlBody = "<strong>This is an HTML Message</strong>";
    //            String textBody = "This is a Text Message.";
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress(username));
    //            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(addto));
    //            message.setSubject("Testing Subject");
    //            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    //            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    //            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    //            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    //            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    //            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    //            CommandMap.setDefaultCommandMap(mc);
    //            message.setText(htmlBody);
    //            message.setContent(textBody, "text/html");
    //            Transport.send(message);
    //
    //            System.out.println("Done");
    //
    //        } catch (MessagingException e) {
    //            e.printStackTrace();
    //        }

    //        final String fromEmail = "finance@wendytour"; //requires valid gmail id
    //        final String password = "wendytr"; // correct password for gmail id
    //        final String toEmail = "wee.chonnasith@gmail.com"; // can be any email id 
    //         
    //        System.out.println("TLSEmail Start");
    //        Properties props = new Properties();
    //        props.put("mail.smtp.host", ""); //SMTP Host
    //        props.put("mail.smtp.port", "587"); //TLS Port
    //        props.put("mail.smtp.auth", "true"); //enable authentication
    //        props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
    //         
    //                //create Authenticator object to pass in Session.getInstance argument
    //        Authenticator auth = new Authenticator() {
    //            //override the getPasswordAuthentication method
    //            protected PasswordAuthentication getPasswordAuthentication() {
    //                return new PasswordAuthentication(fromEmail, password);
    //            }
    //        };
    //        Session session = Session.getInstance(props, auth);
    //         
    //        EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
    //         

}

From source file:br.com.rp.services.EmailService.java

private static HtmlEmail configurarEmailPadrao() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(465);//from  ww  w  .ja  v a  2 s  .  co m
    email.setAuthentication(ENDERECO_EMAIL, SENHA);
    email.setSSLOnConnect(true);
    email.setCharset(StandardCharsets.UTF_8.toString());
    email.setFrom(ENDERECO_EMAIL, "Sistema VBANK");
    return email;
}

From source file:de.maklerpoint.office.Marketing.Tools.SendNewsletter.java

/**
 *
 * @param nl//from www  .  ja v a 2s. c  om
 * @param temail
 * @throws EmailException
 */

public static void sendTestNewsletter(NewsletterObj nl, String temail) throws EmailException {

    HtmlEmail email = new HtmlEmail();
    email.setHostName(Config.get("mailHost", null));

    if (Config.getConfigInt("mailPort", 25) != 25)
        email.setSmtpPort(Config.getConfigInt("mailPort", 25));

    if (Config.getConfigBoolean("mailAuth", true))
        email.setAuthentication(Config.get("mailUser", null), Config.get("mailPassword", null));

    email.setFrom(nl.getSenderMail(), nl.getSender());
    email.setSubject(nl.getSubject());
    email.setHtmlMsg(nl.getText());
    email.setTextMsg("Ihr E-Mail Client untersttzt keine HTML Nachrichten.");

    email.addTo(temail);
    email.send();
}

From source file:de.maklerpoint.office.Marketing.Tools.SendNewsletter.java

/**
 * //from www .  j av a  2  s  .  com
 * @param nl
 * @param sub
 * @throws EmailException
 */

public static void sendNewsletter(NewsletterObj nl, NewsletterSubscriberObj[] sub) throws EmailException {

    for (int i = 0; i < sub.length; i++) {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(Config.get("mailHost", null));

        if (Config.getConfigInt("mailPort", 25) != 25)
            email.setSmtpPort(Config.getConfigInt("mailPort", 25));

        if (Config.getConfigBoolean("mailAuth", true))
            email.setAuthentication(Config.get("mailUser", null), Config.get("mailPassword", null));

        email.setFrom(nl.getSenderMail(), nl.getSender());
        email.setSubject(nl.getSubject());
        email.setHtmlMsg(nl.getText());
        email.setTextMsg("Ihr E-Mail Client untersttzt keine HTML Nachrichten.");

        email.addTo(sub[i].getEmail(), sub[i].getName());
        email.send();
    }
}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * HtmlEmail/*  www  . j  a  va 2 s . com*/
 * 
 * @return HtmlEmail
 */
@SuppressWarnings("PMD.EmptyCatchBlock")
private static HtmlEmail getEmail() {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(SMTP_HOST);
    email.setSmtpPort(SMTP_PORT);
    if (StringUtils.isNotBlank(SMTP_USERNAME) && StringUtils.isNotBlank(SMTP_PASSWORD)) {
        email.setAuthentication(SMTP_USERNAME, SMTP_PASSWORD);
    }
    try {
        Session session = email.getMailSession();
        session.getProperties().setProperty("mail.smtp.ehlo", "true");
    } catch (EmailException e) {
        // do nothing
    }
    if (StringUtils.isNotBlank(SMTP_MAIL_CHARSET)) {
        email.setCharset(SMTP_MAIL_CHARSET);
    }
    return email;
}

From source file:com.baifendian.swordfish.common.mail.MailSendUtil.java

/**
 * ??/*w w w.  j  ava 2  s . co  m*/
 *
 * @param receivers
 * @param title
 * @param content
 * @return
 */
public static boolean sendMails(Collection<String> receivers, String title, String content) {
    if (receivers == null) {
        LOGGER.error("Mail receivers is null.");
        return false;
    }

    receivers.removeIf((from) -> (StringUtils.isEmpty(from)));

    if (receivers.isEmpty()) {
        LOGGER.error("Mail receivers is empty.");
        return false;
    }

    // ?? email
    HtmlEmail email = new HtmlEmail();

    try {
        //  SMTP ?????, 163 "smtp.163.com"
        email.setHostName(mailServerHost);

        email.setSmtpPort(mailServerPort);

        // ?
        email.setCharset("UTF-8");
        // 
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        // ??
        email.setFrom(mailSender, mailSender);
        // ???????-??????
        email.setAuthentication(mailSender, mailPasswd);
        // ???
        email.setSubject(title);
        // ???? HtmlEmail? HTML 
        email.setMsg(content);
        // ??
        email.send();

        return true;
    } catch (Throwable e) {
        LOGGER.error("Send email to {} failed", StringUtils.join(",", receivers), e);
    }

    return false;
}

From source file:ca.ualberta.physics.cssdp.auth.service.EmailServiceImpl.java

public void sendEmail(String from, String to, String subject, String body) {

    try {//from   w w w.  j a v a  2 s  .co  m

        String host = AuthServer.properties().getString("smtpHost");
        int port = AuthServer.properties().getInt("smtpPort");
        final String user = AuthServer.properties().getString("smtpUsername");
        final String password = AuthServer.properties().getString("smtpPassword");
        String systemEmail = AuthServer.properties().getString("systemEmailAddress");
        boolean useSSL = AuthServer.properties().getBoolean("smtpUseSSL");
        boolean debug = AuthServer.properties().getBoolean("smtpDebug");

        HtmlEmail msg = new HtmlEmail();
        msg.setHostName(host);
        msg.setAuthentication(user, password);
        msg.setSmtpPort(port);
        msg.setSSL(useSSL);
        msg.setDebug(debug);
        msg.setSubject("Password Reset Request");
        msg.addTo(to);
        msg.setFrom(systemEmail);
        msg.setHtmlMsg(body);
        msg.send();

    } catch (Exception e) {
        e.printStackTrace();
        throw Throwables.propagate(Throwables.getRootCause(e));
    } finally {
    }

}

From source file:com.elexcode.emailservicelibrary.service.EmailSenderServiceImpl.java

@Override
public void sendEmail(EmailObject emailObject) throws Exception {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);//from ww w  .  j a va  2  s .com
    email.setSmtpPort(port);
    email.setAuthentication(username, password);
    for (String recipient : emailObject.getRecipients()) {
        email.addTo(recipient);
    }
    email.setFrom(username);
    email.setSubject(emailObject.getSubject());
    if (checkStringNotNullNotEmpty(emailObject.getHtmlMsg())) {
        email.setHtmlMsg(emailObject.getHtmlMsg());
    } else {
        if (checkStringNotNullNotEmpty(emailObject.getMessage())) {
            email.setTextMsg(emailObject.getMessage());
        }
    }
    email.setDebug(false);
    email.setTLS(true);
    email.setSSL(true);
    email.send();
}

From source file:org.meruvian.yama.webapi.config.EmailConfig.java

@Bean
@Scope("prototype")
public HtmlEmail email() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(props.getProperty("host"));
    email.setSmtpPort(props.getProperty("port", Integer.class, 0));
    email.setAuthentication(props.getProperty("username"), props.getProperty("password"));
    email.setFrom(props.getProperty("from_email"), props.getProperty("from_alias"));
    email.setSSLOnConnect(props.getProperty("ssl", Boolean.class, false));
    email.setStartTLSEnabled(props.getProperty("tls", Boolean.class, false));

    return email;
}

From source file:com.cerebro.gorgone.commons.SendConfEmail.java

public SendConfEmail(String address, String confCode) {

    logger.info("Invio della mail di conferma");
    // Leggo i parametri di invio
    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        try {// www.  jav a2  s  .  com
            logger.info("Carico il file .properties");
            props.load(config);
        } catch (Exception ex) {
            logger.error("Errore nel caricamento del file .properties: " + ex.getMessage());
        }
    }
    smtp_host = props.getProperty(ConfigProperties.SMTP_HOST);
    smtp_port = Integer.getInteger(props.getProperty(ConfigProperties.SMTP_PORT));
    smtp_user = props.getProperty(ConfigProperties.SMTP_USER);
    smtp_pwd = props.getProperty(ConfigProperties.SMTP_PWD);
    smtp_security = Boolean.parseBoolean(ConfigProperties.SMTP_SECURITY);
    // Creo la mail
    HtmlEmail email = new HtmlEmail();
    try {
        email.setHostName(smtp_host);
        email.setSmtpPort(smtp_port);
        email.setSSLOnConnect(smtp_security);
        email.setAuthentication(smtp_user, smtp_pwd);
        email.setFrom("gioco@gioco.com", "Gioco");
        email.setSubject("Conferma il tuo indirizzo email " + confCode);
        email.addTo(address);
        email.setMsg("Messaggio della mail");
        email.send();
        logger.info("Email inviata");
    } catch (EmailException ex) {
        logger.error("Errore nell'invio della mail");
        logger.error(ex.getMessage());
    }
}