send Email and set up the session - Java Network

Java examples for Network:EMail

Description

send Email and set up the session

Demo Code


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class Main{
    static String emailServerIp = "";
    static String emailFrom = "";
    static String emailUserName = "";
    static String emailPassword = "";
    public static void sendEmail(String content, String subject,
            String emailTo) {//from   w w  w .ja  v a 2  s  .c o m
        MyAuthenticator authenticator = null;
        try {
            authenticator = new MyAuthenticator(emailUserName,
                    emailPassword);
            boolean sessionDebug = false;
            String[] emailTos = emailTo.split(";");
            Properties props = System.getProperties();
            props.put("mail.smtp.localhost", "127.0.0.1");
            props.put("mail.smtp.auth", "true");
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
            props.put("mail.smtp.host", emailServerIp);
            props.put("mail.mime.charset", "utf-8");

            Session session = Session.getDefaultInstance(props,
                    authenticator);
            session.setDebug(sessionDebug);

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(emailFrom));
            InternetAddress[] address = new InternetAddress[emailTos.length];

            for (int i = 0; i < emailTos.length; i++) {
                address[i] = new InternetAddress(emailTos[i]);
            }
            String nick = "";
            try {
                nick = MimeUtility.encodeText(
                        PropertyUtil.getProperty("email_from_name"),
                        "UTF-8", "B");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            msg.setFrom(new InternetAddress(nick + " <" + emailFrom + ">"));
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSentDate(new Date());
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            msg.setContent(new String(content.getBytes("utf-8"),
                    "iso-8859-1"), "text/html");
            msg.addHeader("Content-Transfer-Encoding", "base64");
            msg.addHeader("Content-Type", "text/html;charset=utf-8");
            msg.saveChanges();
            Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials