郵件推送SSL/TLS加密連接

郵件服務器使用的是未加密的連接,使用未加密網絡發送敏感信息可能會被惡意攻擊者通過攔截網絡通信讀取並修改信息。郵件發送加密通道分爲SSL和TLS兩種方式,SSL“安全套接層”協議,TLS“安全傳輸層”協議,都屬於是加密協議(詳細介紹 點擊這裏),加密模式下各協議端口也發生變化,不同的郵箱可能端口不同,基本上

stmp非SSL默認端口25   SSL加密端口465(網易加密多一個994) 
POP3非SSL端口是110   SSL加密端口995
imap非SSL端口是143     SSL加密端口993

注意網絡策略的同步修改,詳細端口可以查看https://www.cnblogs.com/shangdawei/p/4305989.html,我這裏使用網易163發送

 

SSL加密

注意以下幾個配置

        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

端口號:465

TLS加密

注意以下幾個配置

        properties.put("mail.smtp.starttls.enable", "true"); //開啓tls

端口號:25

示例代碼:

如果需要郵件內識別html代碼,在設置內容使用setContent並制定格式text/html;charset=utf-8,如果不需要識別html直接setText即可

            // 消息   消息內容,"text/html;charset=utf-8"讓其識別html代碼
            messageBodyPart.setContent(msg, "text/html;charset=utf-8");

package com.mail;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

public class SendMailTestMain {

	public static void main(String[] args) {
		
		
		String ACCOUNT = "[email protected]";//發件人
		String MAILPASS = "xxxxx";//發件人,郵箱授權碼
		String host = "smtp.163.com";
		//stmp非SSL加密默認端口25   SSL加密端口465(網易加密多一個994) 
		//POP3非SSL加密端口是110 SSL加密995
		//imap非SSL加密端口是143 SSL加密993
		//https://www.cnblogs.com/shangdawei/p/4305989.html
		int port = 465; 
		String receive = "[email protected]";
		String subject = "郵件發送";
		//指定內容格式"text/html;charset=utf-8"讓其識別html代碼
		String msg = "郵件內容<a href=\"https://blog.csdn.net/myfmyfmyfmyf\">支持標籤</a>";
		String filename = "E:\\測試.doc";//附件
		
		try {
//			//SSL發送郵件
//			port = 465; 
//			boolean flag = SendMailTestMain.sendMailBySSL(ACCOUNT, MAILPASS, host, port,receive, subject, msg, filename);
			
			//TLS發送郵件
			port = 25;
			boolean flag = SendMailTestMain.sendMailByTLS(ACCOUNT, MAILPASS, host, port, receive, subject, msg, filename);
			System.out.println("郵件發送結果:"+flag);
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//使用SSL加密通道
	public static boolean sendMailBySSL(String ACCOUNT,String MAILPASS,String host,int port, String receive, String subject, String msg, String filename) throws GeneralSecurityException {

        // 發件人電子郵箱
        final String from = ACCOUNT;
        // 發件人電子郵箱密碼    這個密碼是郵箱的客戶端授權密碼
        final String pass = MAILPASS;
        // 指定發送郵件的主機爲 smtp.qq.com
        // 獲取系統屬性
        Properties properties = System.getProperties();
        // 設置郵件服務器      
        properties.setProperty("mail.smtp.host", host);
        // 端口號
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 獲取默認session對象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq郵箱服務器賬戶、第三方登錄授權碼
                return new PasswordAuthentication(from, pass); // 發件人郵件用戶名、密碼
            }
        });
        try {
            // 創建默認的 MimeMessage 對象
            MimeMessage message = new MimeMessage(session);
            // Set From: 頭部頭字段   發件人郵箱
            message.setFrom(new InternetAddress(from));
            // Set To: 頭部頭字段 收件人郵箱
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));
            // Set Subject: 主題文字  主題
            message.setSubject(subject);
            // 創建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息   消息內容,"text/html;charset=utf-8"讓其識別html代碼
            messageBodyPart.setContent(msg, "text/html;charset=utf-8");
            // 創建多重消息
            Multipart multipart = new MimeMultipart();
            // 設置文本消息部分
            multipart.addBodyPart(messageBodyPart);
            // 附件部分 添加附件
            messageBodyPart = new MimeBodyPart();
            // 設置要發送附件的文件路徑   filename 是要添加的附件的路徑   如 "E:\測試.doc"
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            // messageBodyPart.setFileName(filename);
            // 處理附件名稱中文(附帶文件路徑)亂碼問題
            messageBodyPart.setFileName(MimeUtility.encodeText(filename));
            multipart.addBodyPart(messageBodyPart);
            // 發送完整消息
            message.setContent(multipart);
            // 發送消息
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }
	
	
	
	//使用TLS加密通道
	public static boolean sendMailByTLS(String ACCOUNT,String MAILPASS,String host,int port, String receive, String subject, String msg, String filename) throws GeneralSecurityException {

        // 發件人電子郵箱
        final String from = ACCOUNT;
        // 發件人電子郵箱密碼    這個密碼是郵箱的客戶端授權密碼
        final String pass = MAILPASS;
        // 指定發送郵件的主機爲 smtp.qq.com
        // 獲取系統屬性
        Properties properties = System.getProperties();
        // 設置郵件服務器      
        properties.setProperty("mail.smtp.host", host);
        // 端口號
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.starttls.enable", "true"); //開啓tls
        // 獲取默認session對象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq郵箱服務器賬戶、第三方登錄授權碼
                return new PasswordAuthentication(from, pass); // 發件人郵件用戶名、密碼
            }
        });
        try {
            // 創建默認的 MimeMessage 對象
            MimeMessage message = new MimeMessage(session);
            // Set From: 頭部頭字段   發件人郵箱
            message.setFrom(new InternetAddress(from));
            // Set To: 頭部頭字段 收件人郵箱
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));
            // Set Subject: 主題文字  主題
            message.setSubject(subject);
            // 創建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息   消息內容,"text/html;charset=utf-8"讓其識別html代碼
            messageBodyPart.setContent(msg, "text/html;charset=utf-8");
            // 創建多重消息
            Multipart multipart = new MimeMultipart();
            // 設置文本消息部分
            multipart.addBodyPart(messageBodyPart);
            // 附件部分 添加附件
            messageBodyPart = new MimeBodyPart();
            // 設置要發送附件的文件路徑   filename 是要添加的附件的路徑   如 "E:\測試.doc"
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            // messageBodyPart.setFileName(filename);
            // 處理附件名稱中文(附帶文件路徑)亂碼問題
            messageBodyPart.setFileName(MimeUtility.encodeText(filename));
            multipart.addBodyPart(messageBodyPart);
            // 發送完整消息
            message.setContent(multipart);
            // 發送消息
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章