indzi
6/11/2017 - 10:10 AM

sendEmail.java

package org.parsysis.base.JAM.bean;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    public void send(String userName, String pass, Properties properties,
                     Boolean smtp, Boolean ssl, String from, String recipients,
                     String subject, String body) {
        Session session = getSession(properties, userName, pass, smtp, ssl);
        sendOperation(session, from, recipients, subject, body);
    }


    private Session getSession(Properties properties, String userName,
                               String pass, Boolean smtp, Boolean ssl) {
        Properties props = new Properties();
        props = properties;
        //        Properties props = new Properties();
        //		props.put("mail.smtp.auth", "true");
        //                props.put("mail.smtp.starttls.enable", "true");
        //		props.put("mail.smtp.host", "smtp.gmail.com");
        //		props.put("mail.smtp.port", "587");

        final String username = userName;
        final String password = pass;
        Session session = null;
        session = Session.getInstance(props, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        return session;
    }

    private void sendOperation(Session session, String from, String recipients,
                               String subject, String body) {
        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO,
                                  InternetAddress.parse(recipients));
            message.setSubject(subject);
            message.setContent(body, "text/html");


            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}