使用JavaMail發送郵件,465端口開啓ssl加密傳輸

package com.wangxin.test;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
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;

/**
 * javaMail的郵件工具類
 * @author wangXgnaw
 *
 */
public class MailUtil {

    /**
     * 使用加密的方式,利用465端口進行傳輸郵件,開啓ssl
     * @param to    爲收件人郵箱
     * @param message    發送的消息
     */
    public static void sendEmil(String to, String message) {
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            //設置郵件會話參數
            Properties props = new Properties();
            //郵箱的發送服務器地址
            props.setProperty("mail.smtp.host", "smtp.sina.com");
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //郵箱發送服務器端口,這裏設置爲465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            final String username = "發送者郵箱用戶名";
            final String password = "發送者郵箱密碼或者郵箱受權碼";
            //獲取到郵箱會話,利用匿名內部類的方式,將發送者郵箱用戶名和密碼受權給jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            //經過會話,獲得一個郵件,用於發送
            Message msg = new MimeMessage(session);
            //設置發件人
            msg.setFrom(new InternetAddress("發件人郵箱"));
            //設置收件人,to爲收件人,cc爲抄送,bcc爲密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject("郵件主題");
            //設置郵件消息
            msg.setText(message);
            //設置發送的日期
            msg.setSentDate(new Date());
            
            //調用Transport的send方法去發送郵件
            Transport.send(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
}
相關文章
相關標籤/搜索