java發送郵件基礎方法(另附部分主流郵箱服務器地址、端口及授權碼設置方法)


java發送郵件基礎方法,可通過重載簡化參數

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
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;

public class MailUtil {

    /**
     * @Description: 使用QQ郵箱發送不帶附件的郵件,收件人郵箱類型不限。
     * @date: 2019年12月17日 下午4:51:01
     * @author: ggwudivs
     * @param subject        郵件標題
     * @param content        郵件內容
     * @param fromUser        發件人郵箱
     * @param fromPass        發件人郵箱密碼,應為16位SMTP口令
     * @param tO_Recipients    收件人郵箱,多個收件人用","分隔
     * @param openSSL        是否開啟SSL
     * @throws UnsupportedEncodingException
     * @throws MessagingException:
     * @return: void
     */
    public static void sendMessage_QQ (String subject, String content, String fromUser, String fromPass, String tO_Recipients, boolean openSSL) throws UnsupportedEncodingException, MessagingException{
        sendMessage(subject, content, fromUser, fromPass, null, tO_Recipients, null, null, "smtp.qq.com", openSSL?"465":"587", null, openSSL);
    }
    
    /**
     * @Description: 使用QQ郵箱發送帶附件的郵件,收件人郵箱類型不限。
     * @date: 2019年12月17日 下午5:25:14
     * @author: ggwudivs
     * @param subject                郵件標題
     * @param content                郵件內容
     * @param fromUser                發件人郵箱
     * @param fromPass                發件人郵箱密碼,應為16位SMTP口令
     * @param tO_Recipients            收件人郵箱,多個收件人用","分隔
     * @param attachmentFilesPath    郵件附件路徑,多個附件用","分隔
     * @param openSSL                是否開啟SSL
     * @throws UnsupportedEncodingException
     * @throws MessagingException:
     * @return: void
     */
    public static void sendMessage_QQ (String subject, String content, String fromUser, String fromPass, String tO_Recipients, String attachmentFilesPath, boolean openSSL) throws UnsupportedEncodingException, MessagingException{
        sendMessage(subject, content, fromUser, fromPass, null, tO_Recipients, null, null, "smtp.qq.com", openSSL?"465":"587", attachmentFilesPath, openSSL);
    }
    
    /**
     * @Description: smtp發送郵件
     * @date: 2019年12月17日 下午3:22:35
     * @author: ggwudivs
     * @param subject                郵件標題
     * @param content                郵件文本內容
     * @param fromUser                發件人郵箱
     * @param fromPass                發件人郵箱密碼,QQ郵箱應為16位SMTP口令
     * @param nickname                發件人昵稱
     * @param tO_Recipients            收件人郵箱,多個收件人用","分隔
     * @param cC_Recipients            抄送人郵箱,多個抄送人用","分隔
     * @param bCC_Recipients        密送人郵箱,多個密送人用","分隔
     * @param smtpHost                smtp服務器地址
     * @param smtpPort                smtp服務器端口
     * @param attachmentFilesPath    郵件附件路徑,多個附件用","分隔
     * @throws MessagingException
     * @throws UnsupportedEncodingException:
     * @return: void
     */
    public static void sendMessage(String subject, String content, String fromUser, String fromPass, String nickname, String tO_Recipients, String cC_Recipients, String bCC_Recipients, String smtpHost, String smtpPort, String attachmentFilesPath, boolean openSSL) throws MessagingException, UnsupportedEncodingException {  
        //創建Properties類,用於記錄郵箱的一些屬性
        Properties props = new Properties();
        //表示SMTP發送郵件,必須進行身份驗證
        props.put("mail.smtp.auth", "true");
        //SMTP服務器地址
        props.put("mail.smtp.host", smtpHost);
        //是否開啟SSL
        if(!openSSL){
            //SMTP服務器端口號
            props.put("mail.smtp.port", smtpPort);
        }else{
            //SMTP服務器ssl端口號
            props.setProperty("mail.smtp.socketFactory.port", smtpPort);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }

        //構建授權信息,用於進行SMTP進行身份驗證
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                //發件人賬號,發件人密碼(QQ郵箱應為16位SMTP口令)
                return new PasswordAuthentication(fromUser, fromPass);
            }
        };
        
        //使用環境屬性和授權信息,創建郵件會話
        Session mailSession = Session.getInstance(props, authenticator);
        
        //創建郵件消息
        MimeMessage message = new MimeMessage(mailSession);
        
        //設置發件人,有昵稱時同時設置昵稱
        try {
            message.setFrom((nickname==null||"".equals(nickname))?new InternetAddress(fromUser):new InternetAddress(fromUser, nickname, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //設置一個或多個收件人
        message.setRecipients(RecipientType.TO, tO_Recipients);
        
        //設置一個或多個抄送人
        message.setRecipients(RecipientType.CC, cC_Recipients);
        
        //設置一個或多個密送人
        message.setRecipients(RecipientType.BCC, bCC_Recipients);

        //設置郵件標題
        message.setSubject(subject);

        //設置郵件的內容
        if(attachmentFilesPath == null || "".equals(attachmentFilesPath)){
            //設置郵件的正文文本
            message.setContent(content, "text/html;charset=UTF-8");
        }else{
            //向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
            Multipart multipart = new MimeMultipart();
            
            //添加郵件文本內容
            BodyPart contentBodyPart = new MimeBodyPart();
            contentBodyPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentBodyPart);
            
            //添加郵件附件內容
            BodyPart attachmentBodyPart = new MimeBodyPart();
            String[] attachmentFiles = attachmentFilesPath.split(",");
            for (String attachmentFile : attachmentFiles) {
                if (attachmentFile != null && !"".equals(attachmentFile)) {
                    attachmentBodyPart = new MimeBodyPart(); 
                    
                    //根據附件路徑獲取文件,
                    FileDataSource dataSource = new FileDataSource(new File(attachmentFile));
                    attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                    
                    //MimeUtility.encodeWord可以避免文件名亂碼
                    String strFileName=dataSource.getFile().getName();
                    attachmentBodyPart.setFileName(MimeUtility.encodeText(strFileName));  
                    
                    multipart.addBodyPart(attachmentBodyPart);
                }
            }
            
            //設置郵件的正文內容
            message.setContent(multipart);
        }
        
        //發送郵件
        Transport.send(message);
    }  
}
郵箱類型 SMTP服務器地址 普通端口 SSL端口 服務器配置參考地址
QQ郵箱 smtp.qq.com 587 465 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=167
阿里企業郵箱 smtp.qiye.aliyun.com 25 465 http://mailhelp.mxhichina.com/smartmail/detail.vm?knoId=5871700
網易163免費郵箱 smtp.163.com 25 465/994 https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac22dc0e9af8168582a
網易企業郵箱 smtp.qiye.163.com 25 994 https://qiye.163.com/help/client-profile.html
網易免費企業郵箱 smtp.ym.163.com 25 994 http://app.ym.163.com/ym/help/help.html

 tips:

QQ郵箱需先設置獨立密碼才能使用smtp功能(https://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001220&&id=28)。

QQ郵箱設置方法:設置--賬戶--賬戶安全--獨立密碼。

網易163免費郵箱同QQ郵箱一樣,需先設置授權碼才能使用smtp功能(https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac24a2130dd2fad05b1

網易163免費郵箱開啟授權碼方法:https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac2cda80145a1742516

網易企業郵箱在開啟客戶端授權密碼的功能時才需要設置客戶端授權碼:https://qiye.163.com/help/3f85a9.html

網易企業郵箱開啟授權碼方法:https://qiye.163.com/help/af988e.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM