Java Mail 郵件發(fā)送(一):Demo

上周公司的項(xiàng)目要求開發(fā)郵件發(fā)送功能。自己在網(wǎng)上跟著教程邊學(xué)邊做了一下午,現(xiàn)在基本開發(fā)完成了。由于一個(gè)同事也想看下該怎么寫,順便學(xué)習(xí)下。所以我就寫成了一遍教程,順便鞏固下郵件發(fā)送里面的內(nèi)容。


Demo

第一步,我們先寫個(gè)Demo,用最快的方式最少的代碼向你展示Java Mail 是如何工作的。
我的開發(fā)環(huán)境是:

  1. JDK1.6
  2. java-mail.jar 1.45

構(gòu)建一個(gè)簡(jiǎn)單的郵件發(fā)送,一共需要四步:

1.配置發(fā)件人郵箱信息以及創(chuàng)建一個(gè)存放SMTP服務(wù)器地址等參數(shù)的Java 配置類。
        String sendEmailAccount = "Example@outlook.com";          //發(fā)件人郵箱
        String sendEmailPassword = "password";          //發(fā)件人密碼
        String sendEmailSMTPHost = "smtp-mail.outlook.com";       // 發(fā)件人郵箱的 SMTP 服務(wù)器地址, 此處為Outlook郵箱的SMTP服務(wù)器
        String receiveMailAccount = "Example@163.com";          // 收件人郵箱
        final String smtpPort = "587";                   //默認(rèn)端口號(hào)設(shè)置為587,也可以設(shè)置為465,具體取決于SMTP服務(wù)器要求的端口號(hào)
        Properties props = new Properties();                    // 使用Java配置類進(jìn)行配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的協(xié)議(JavaMail規(guī)范要求)
        props.setProperty("mail.smtp.host", sendEmailSMTPHost);   // 發(fā)件人的郵箱的 SMTP 服務(wù)器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要請(qǐng)求認(rèn)證
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort );  
2.創(chuàng)建一個(gè)同郵件服務(wù)器交互的session
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                                 // debug模式下會(huì)在控制臺(tái)打印出日志,如果不想看日志應(yīng)該設(shè)置為false
3.創(chuàng)建一封格式化的郵件
        // 1. 創(chuàng)建一封郵件
        MimeMessage message = new MimeMessage(session);
        // 2. From: 發(fā)件人
        message.setFrom(new InternetAddress(sendEmailAccount , "ExampleFrom", "UTF-8"));
        // 3. To: 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount, "ExampleUser", "UTF-8"));
        // 4. Subject: 郵件主題(標(biāo)題有廣告嫌疑,避免被郵件服務(wù)器誤認(rèn)為是濫發(fā)廣告以至返回失敗,請(qǐng)修改標(biāo)題)
        message.setSubject("", "UTF-8");
        // 5. Content: 郵件正文
        message.setContent("<h3>This is a test email.</h3>", "text/html;charset=UTF-8");
        // 6. 設(shè)置郵件發(fā)件時(shí)間
        message.setSentDate(new Date());
        // 7. 保存設(shè)置
        message.saveChanges();
4.發(fā)送郵件
        // 1. 根據(jù) Session 獲取郵件傳輸對(duì)象
        Transport transport = session.getTransport();
        // 2. 使用 郵箱賬號(hào) 和 密碼 連接郵件服務(wù)器
        transport.connect(myEmailAccount, myEmailPassword);
        // 3. 發(fā)送郵件, 發(fā)到所有的收件地址, message.getAllRecipients() 獲取到的是在創(chuàng)建郵件對(duì)象時(shí)添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        // 4. 關(guān)閉連接
        transport.close();
完整代碼

整合以上步驟的完整代碼如下:

import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailExample {
    public static void main(String[] args) throws Exception {
        /**
         * 1.配置發(fā)件人郵箱信息以及創(chuàng)建一個(gè)Java 配置類存放SMTP服務(wù)器地址等參數(shù)。
         */
        String sendEmailAccount = "Example@outlook.com";                            // 發(fā)件人郵箱
        String sendEmailPassword = "password";                                      // 發(fā)件人密碼
        String sendEmailSMTPHost = "smtp-mail.outlook.com";                         // 發(fā)件人郵箱的 SMTP 服務(wù)器地址, 此處為Outlook郵箱的SMTP服務(wù)器
        String receiveMailAccount = "Example@163.com";                              // 收件人郵箱
        Properties props = new Properties();                                        // 使用Java配置類進(jìn)行配置
        props.setProperty("mail.transport.protocol", "smtp");                       // 使用的協(xié)議(JavaMail規(guī)范要求)
        props.setProperty("mail.smtp.host", sendEmailSMTPHost);                     // 發(fā)件人的郵箱的 SMTP 服務(wù)器地址
        props.setProperty("mail.smtp.auth", "true");                                // 需要請(qǐng)求認(rèn)證
        final String smtpPort = "465";                                              // 默認(rèn)端口號(hào)設(shè)置為587,也可以設(shè)置為465,具體取決于SMTP服務(wù)器要求的端口號(hào)
                props.setProperty("mail.smtp.port",smtpPort );
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort );                       
        
        /**
         * 2.創(chuàng)建一個(gè)同郵件服務(wù)器交互的session
         */
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);                                  // 1. 創(chuàng)建一封郵件
        message.setFrom(new InternetAddress(sendEmailAccount, "ExampleFrom", "UTF-8"));  // 2. From: 發(fā)件人
        message.setRecipient(MimeMessage.RecipientType.TO, 
                new InternetAddress(receiveMailAccount, "ExampleUser", "UTF-8"));        // 3. To: 收件人
        message.setSubject("", "UTF-8");                                                 // 4. Subject: 郵件主題(標(biāo)題有廣告嫌疑,避免被郵件服務(wù)器誤認(rèn)為是濫發(fā)廣告以至返回失敗,請(qǐng)修改標(biāo)題)
        message.setContent("<h3>This is a test email.</h3>", "text/html;charset=UTF-8"); // 5. Content: 郵件正文
        message.setSentDate(new Date());                                                 // 6. 設(shè)置郵件發(fā)件時(shí)間
        message.saveChanges();                                                           // 7. 保存設(shè)置
        
        /**
         * 3.創(chuàng)建一封格式化的郵件
         */
        Transport transport = session.getTransport();                                    // 1. 根據(jù) Session 獲取郵件傳輸對(duì)象
        transport.connect(sendEmailAccount, sendEmailPassword);                          // 2. 使用 郵箱賬號(hào) 和 密碼 連接郵件服務(wù)器
        transport.sendMessage(message, message.getAllRecipients());                      // 3. 發(fā)送郵件, 發(fā)到所有的收件地址, message.getAllRecipients() 獲取到的是在創(chuàng)建郵件對(duì)象時(shí)添加的所有收件人, 抄送人,
        transport.close();                                                               // 4. 關(guān)閉連接
    }
}

這樣一個(gè)簡(jiǎn)單的JavaMail的Demo就完成了。快去測(cè)試下吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容