集册 Java实例教程 发送电子邮件并设置会话

发送电子邮件并设置会话

欢马劈雪     最近更新时间:2020-01-02 10:19:05

395
发送电子邮件并设置会话
/*来自 
 时   代     Java  公  众  号 - nowjava.com*/


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,/*来 自 时代Java公众号 - N o w J a  v a . c o m*/

            String emailTo) {

        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, 
展开阅读全文