Java實現QQ郵件傳送郵件工具類

bd2star發表於2018-02-13

1、開啟SMTP服務
在 QQ 郵箱裡的 設定->賬戶裡開啟 SMTP 服務
這裡寫圖片描述

注意開啟完之後,QQ 郵箱會生成一個授權碼,在程式碼裡連線郵箱使用這個授權碼而不是原始的郵箱密碼,這樣可以避免使用明文密碼。

這裡寫圖片描述

2、下載依賴的 jar 包

官方下載地址 http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.7-oth-JPR
解壓完之後,通常我們只需要其中的mail.jar,把它加到我們 java 工程的依賴包中。

package com.weixiaoinfo.framework.util;

import com.sun.mail.util.MailSSLSocketFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.*;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
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.AddressException;
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;

public class SendMailUtil {
    private String username = null;
    private String password = null;
    private Authenticator auth = null;
    private MimeMessage mimeMessage =null;
    private Properties pros = null;
    private Multipart multipart = null;
    private BodyPart bodypart= null;
    /**
     * 初始化賬號密碼並驗證
     * 建立MimeMessage物件
     * 傳送郵件必須的步驟:1
     * @param username
     * @param password
     */
    public SendMailUtil(String username,String password){
        this.username = username;
        this.password = password;
    }

    /**
     * 設定email系統引數
     * 接收一個map集合key為string型別,值為String
     * 傳送郵件必須的步驟:2
     * @param map
     */
    public void setPros(Map<String,String> map) throws GeneralSecurityException {
        pros = new Properties();
        //可以採用下面埠號  或者使用ssl加密
//        MailSSLSocketFactory sf = new MailSSLSocketFactory();
//        sf.setTrustAllHosts(true);
//        pros.put("mail.smtp.ssl.enable", "true");
//        pros.put("mail.smtp.ssl.socketFactory", sf);
        for(Map.Entry<String,String> entry:map.entrySet()){
            pros.setProperty(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 初始化MimeMessage物件 存放郵件內容部分
     * 傳送郵件必須的步驟:3
     */
    public void initMessage(){
        this.auth = new Email_Autherticator();
        Session session = Session.getDefaultInstance(pros,auth);
        session.setDebug(true); //設定獲取 debug 資訊
        mimeMessage = new MimeMessage(session);
    }
    /**
     * 驗證賬號密碼
     * 傳送郵件必須的步驟
     *
     */
    public class Email_Autherticator extends Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    }
    /**
     * 設定傳送郵件的基本引數(去除繁瑣的郵件設定)
     * @param sub 設定郵件主題
     * @param text 設定郵件文字內容
     * @param rec 設定郵件接收人
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{
        mimeMessage.setSubject(sub);
        mimeMessage.setText(text);
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
        mimeMessage.setSentDate(new Date());
        mimeMessage.setFrom(new InternetAddress(username,username));
    }
    /**
     * 設定主題
     * @param subject
     * @throws MessagingException
     */
    public void  setSubject(String subject) throws MessagingException{
        mimeMessage.setSubject(subject);
    }
    /**
     * 設定日期
     * @param date
     * @throws MessagingException
     */
    public void  setDate(Date date) throws MessagingException{
        mimeMessage.setSentDate(new Date());
    }
    /**
     * 設定郵件文字內容
     * @param text
     * @throws MessagingException
     */
    public void setText(String text) throws MessagingException{
        mimeMessage.setText(text);
    }
    /**
     * 設定郵件頭部
     * @param arg0
     * @param arg1
     * @throws MessagingException
     */
    public void setHeader(String arg0,String arg1) throws MessagingException{
        mimeMessage.setHeader(arg0, arg1);
    }
    /**
     * 設定郵件接收人地址 <單人傳送>
     * @param recipient
     * @throws MessagingException
     */
    public void setRecipient(String recipient) throws MessagingException{
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }
    /**
     * 設定郵件接收人地址 <多人傳送>
     * @param recs  收件人list集合
     * @throws MessagingException
     * @throws AddressException
     */
    public String setRecipients(List<String> recs) throws AddressException, MessagingException{
        if(recs.isEmpty()){
            return "接收人地址為空!";
        }
        for(String str:recs){
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
        }
        return "加入接收人地址成功!";
    }
    /**
     * 設定郵件接收人地址 <多人傳送>
     * @param sb 收件人字串集
     * @throws MessagingException
     * @throws AddressException
     */
    @SuppressWarnings("static-access")
    public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{
        if(sb==null||"".equals(sb)){
            return "字串資料為空!";
        }
        Address []address = new InternetAddress().parse(sb.toString());
        mimeMessage.addRecipients(Message.RecipientType.TO, address);
        return "收件人加入成功";
    }
    /**
     * 設定郵件傳送人的名字
     * @param from
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{
        mimeMessage.setFrom(new InternetAddress(username,from));
    }
    /**
     * 傳送郵件<單人傳送>
     * return 是否傳送成功
     * @throws MessagingException
     */
    public String sendMessage() throws MessagingException{
        Transport.send(mimeMessage);
        return "success";
    }
    /**
     * 設定附件
     * @param file 傳送檔案的路徑
     */
    public void setMultipart(String file) throws MessagingException, IOException{
        if(multipart==null){
            multipart = new MimeMultipart();
        }
        multipart.addBodyPart(writeFiles(file));
        mimeMessage.setContent(multipart);
    }
    /**
     * 設定附件<新增多附件>
     * @param fileList<接收List集合>
     * @throws MessagingException
     * @throws IOException
     */
    public void setMultiparts(List<String> fileList) throws MessagingException, IOException{
        if(multipart==null){
            multipart = new MimeMultipart();
        }
        for(String s:fileList){
            multipart.addBodyPart(writeFiles(s));
        }
        mimeMessage.setContent(multipart);
    }
    /**
     * 傳送文字內容,設定編碼方式
     * <方法與傳送附件配套使用>
     * <傳送普通的文字內容請使用setText()方法>
     * @param s
     * @param type
     * @throws MessagingException
     */
    public void setContent(String s,String type) throws MessagingException{
        if(multipart==null){
            multipart = new MimeMultipart();
        }
        bodypart = new MimeBodyPart();
        bodypart.setContent(s, type);
        multipart.addBodyPart(bodypart);
        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();
    }
    /**
     * 讀取附件
     * @param filePath
     * @return
     * @throws IOException
     * @throws MessagingException
     */
    public BodyPart writeFiles(String filePath)throws IOException, MessagingException{
        File file = new File(filePath);
        if(!file.exists()){
            throw new IOException("檔案不存在!請確定檔案路徑是否正確");
        }
        bodypart = new MimeBodyPart();
        DataSource dataSource = new FileDataSource(file);
        bodypart.setDataHandler(new DataHandler(dataSource));
        //檔名要加入編碼,不然出現亂碼
        bodypart.setFileName(MimeUtility.encodeText(file.getName()));
        return bodypart;
    }

    public static void main(String[] args) throws MessagingException, GeneralSecurityException, IOException {
        Map<String,String> map= new HashMap<String,String>();
        SendMailUtil mail = new SendMailUtil("***@qq.com","*您的授權碼*");
        map.put("mail.smtp.auth", "true");
        map.put("mail.smtp.host", "smtp.qq.com");
        //埠號,QQ郵箱需要使用SSL,埠號465或587
        map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        map.put("mail.smtp.port", "465");
        map.put("mail.smtp.socketFactory.port", "465");
        mail.setPros(map);
        mail.initMessage();
        /*
         * 新增收件人有三種方法:
         * 1,單人新增(單人傳送)呼叫setRecipient(str);傳送String型別
         * 2,多人新增(群發)呼叫setRecipients(list);傳送list集合型別
         * 3,多人新增(群發)呼叫setRecipients(sb);傳送StringBuffer型別
         */
        //傳送方式1
        mail.setRecipient("***@qq.com");
        //傳送方式2
//        List<String> list = new ArrayList<String>();
//        list.add("***@qq.com");
//        list.add("***@163.com");
//        mail.setRecipients(list);
        //傳送方式3
//        String defaultStr = "***@qq.com,***@163.com";
//        StringBuffer sb = new StringBuffer();
//        sb.append(defaultStr);
//        sb.append(",***@qq.com");
//        mail.setRecipients(sb);
        mail.setSubject("我是郵箱標題呀");
        mail.setText("我是郵箱內容呀");
        mail.setDate(new Date());
        mail.setFrom("我是發件人的名字呀");
//      mail.setMultipart("D:你你你.txt");
//        mail.setContent("謝謝合作123", "text/html; charset=UTF-8");
//        List<String> fileList = new ArrayList<String>();
//        fileList.add("D:123.png");
//        fileList.add("D:123.txt");
//        fileList.add("D:dstz.sql");
//        fileList.add("D:軟體配置要求.doc");
//        mail.setMultiparts(fileList);
        System.out.println(mail.sendMessage());
    }

}

下面是另一個版本的簡易版的程式碼

package com.weixiaoinfo.framework.util;

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

public class SendMail {
    public static void main(String[] args) throws MessagingException, GeneralSecurityException {
        Properties props = new Properties();
        //開啟 SSL 加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 開啟debug除錯
        props.setProperty("mail.debug", "true");
        // 傳送伺服器需要身份驗證
        props.setProperty("mail.smtp.auth", "true");
        // 設定郵件伺服器主機名
        props.setProperty("mail.host", "smtp.qq.com");
        // 傳送郵件協議名稱
        props.setProperty("mail.transport.protocol", "smtp");

        Session session = Session.getInstance(props);

        //郵件內容部分
        Message msg = new MimeMessage(session);
        msg.setSubject("我是標題呀");
        StringBuilder builder = new StringBuilder();
        builder.append("我是您要傳送內容");
        builder.append("可在內容追加哦");
        builder.append("\n data " + new Date());
        msg.setText(builder.toString());
        //郵件傳送者
        msg.setFrom(new InternetAddress("***@qq.com"));

        //傳送郵件
        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "*您的郵箱*", "*授權碼*");
        //接收人的郵箱地址
        transport.sendMessage(msg, new Address[]{new InternetAddress("***@163.com")});
        transport.close();
    }

}

參考①自:http://blog.csdn.net/never_cxb/article/details/50543289
參考②自:http://blog.csdn.net/Coding_One/article/details/51354456
感謝兩位作者的辛苦勞動

相關文章