Java發(fā)送郵件:使用JavaMail API發(fā)送電子郵件
作者:Stevedash
發(fā)表于:2023年8月13日 15點(diǎn)48分
來(lái)源:Java 發(fā)送郵件 | 菜鳥(niǎo)教程 (runoob.com)
電子郵件在現(xiàn)代通信中扮演著至關(guān)重要的角色,而在Java編程中,我們可以利用JavaMail API來(lái)方便地實(shí)現(xiàn)發(fā)送電子郵件的功能。本篇博客將向您介紹如何使用JavaMail API來(lái)發(fā)送電子郵件,以及一些關(guān)鍵概念和實(shí)用示例。
JavaMail API基本概念:
? JavaMail API是Java平臺(tái)上用于發(fā)送和接收電子郵件的強(qiáng)大庫(kù)。它提供了一組類和方法,可以用于創(chuàng)建、發(fā)送和處理電子郵件。使用JavaMail API,您可以輕松地在Java應(yīng)用程序中集成電子郵件功能,從而實(shí)現(xiàn)諸如發(fā)送提醒、通知和報(bào)告等任務(wù)。
Java 發(fā)送郵件
? 使用Java應(yīng)用程序發(fā)送 E-mail 十分簡(jiǎn)單,但是首先你應(yīng)該在你的機(jī)器上安裝 JavaMail API 和Java Activation Framework (JAF) 。
你也可以使用菜鳥(niǎo)教程提供的下載鏈接:
- JavaMail mail.jar 1.4.5
- JAF(版本 1.1.1) activation.jar
下載這倆個(gè)Jar文件。您需要把 mail.jar 和 activation.jar 文件添加到您的 項(xiàng)目中的lib中,然后添加進(jìn)項(xiàng)目Project Structure?Libraies?“+”選擇上面?zhèn)z個(gè)架包
類型 | 服務(wù)器名稱 | 服務(wù)器地址(163為例) | SSL協(xié)議端口 | 非SSL協(xié)議端口號(hào) | TSL協(xié)議端口 |
---|---|---|---|---|---|
收件服務(wù)器 | POP | pop.163.com | 995 | 110 | |
收件服務(wù)器 | IMAP | imap.163.com | 993 | 143 | |
發(fā)件服務(wù)器 | SMTP | smtp.163.com | 465/994 | 25 | 587 |
騰訊企業(yè)郵箱服務(wù)器地址:smtp.exmail.qq.com
騰訊郵箱服務(wù)器地址:smtp.qq.com
常見(jiàn)問(wèn)題以及解決辦法如下:
1、如果出現(xiàn)454 Command not permitted when TLS active 錯(cuò)誤,請(qǐng)檢查你的郵件端口配置的是不是25端口,如果是,請(qǐng)改成465端口,并且需要設(shè)置 mail.smtp.starttls.enable=false,即可解決問(wèn)題。
2、部分郵件提供商smtp登錄密碼不是賬號(hào)密碼,而是授權(quán)碼,務(wù)必注意。使用SSL、TLS這個(gè)一定要注意。
3、550 用戶被鎖定:普通 163 郵箱是無(wú)法通過(guò) smtp.163.com 發(fā)送郵件的,只有 163 VIP 郵箱才行,然后設(shè)置 mail.smtp.host=smtp.vip.163.com
4、550 **Invalid User:**from 必須寫成帶 @ 的郵件格式,且 username 要用 @ 前面的
5、553 authentication is required:需要設(shè)置 mail.smtp.auth=true
步驟概述
以下是使用JavaMail API發(fā)送電子郵件的基本步驟:
- 設(shè)置郵件服務(wù)器屬性:指定SMTP服務(wù)器的主機(jī)名、端口、身份驗(yàn)證等屬性。
- 創(chuàng)建會(huì)話對(duì)象:使用郵件服務(wù)器屬性創(chuàng)建一個(gè)會(huì)話對(duì)象,同時(shí)提供身份驗(yàn)證信息。
- 創(chuàng)建郵件消息:創(chuàng)建一個(gè)郵件消息對(duì)象,設(shè)置發(fā)件人、收件人、主題、內(nèi)容等信息。
- 發(fā)送郵件:使用會(huì)話對(duì)象的
Transport
類發(fā)送郵件消息。
需要用戶名密碼驗(yàn)證郵件發(fā)送實(shí)例:
本實(shí)例以 QQ 郵件服務(wù)器為例,你需要在登錄QQ郵箱后臺(tái)在"設(shè)置"=》賬號(hào)中開(kāi)啟POP3/SMTP服務(wù) ,如下圖所示:
QQ 郵箱通過(guò)生成授權(quán)碼來(lái)設(shè)置密碼:
示例代碼
①下面是一個(gè)簡(jiǎn)單的Java程序,演示了如何使用JavaMail API發(fā)送一封電子郵件:
// 導(dǎo)入必要的類
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailSender {
public static void main(String[] args) {
// 設(shè)置郵件服務(wù)器屬性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.qq.com"); // 設(shè)置郵件服務(wù)器主機(jī)名
properties.put("mail.smtp.port", "587"); // 設(shè)置郵件服務(wù)器端口號(hào)
properties.put("mail.smtp.auth", "true"); // 啟用身份驗(yàn)證
properties.put("mail.smtp.starttls.enable", "true"); // 啟用 TLS
//properties.put("mail.smtp.socketFactory.port", "465"); // 設(shè)置 SSL 端口
//properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 設(shè)置 SSL Socket Factory
//properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退
// 創(chuàng)建會(huì)話對(duì)象
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@example.com", "your_password");
// 在這里填寫發(fā)送郵件的郵箱地址和密碼/授權(quán)碼
}
});
try {
// 創(chuàng)建郵件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@example.com")); // 設(shè)置發(fā)件人郵箱
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); // 設(shè)置收件人郵箱
message.setSubject("JavaMail API測(cè)試"); // 設(shè)置郵件主題
message.setText("這是一封來(lái)自JavaMail API的測(cè)試郵件。"); // 設(shè)置郵件內(nèi)容
// 發(fā)送郵件
Transport.send(message);
System.out.println("郵件發(fā)送成功!"); // 打印成功信息
} catch (MessagingException e) {
e.printStackTrace(); // 打印異常堆棧信息
}
}
}
下面是對(duì)于參數(shù)的描述:
- type:要被設(shè)置為 TO, CC 或者 BCC,這里 CC 代表抄送、BCC 代表秘密抄送。舉例:
- addresses: 這是 email ID 的數(shù)組。在指定電子郵件 ID 時(shí),你將需要使用 InternetAddress() 方法。
在 Message.RecipientType
枚舉類型中,以下幾個(gè)常量表示不同的收件人類型:
-
TO
: 主要收件人,這些人將直接收到郵件的副本。 CC
: 抄送(Carbon Copy),這些人將收到郵件的副本,但這并不是郵件的主要接收者。BCC
: 密送(Blind Carbon Copy),這些人也將收到郵件的副本,但其他收件人無(wú)法看到他們的地址。
②在使用 JavaMail API 創(chuàng)建郵件消息時(shí),您可以通過(guò)指定這些收件人類型來(lái)將不同的收件人添加到郵件消息中。
例如,message.setRecipients(Message.RecipientType.TO, recipientAddresses)
將主要收件人添加到郵件消息中。同樣,您可以使用相應(yīng)的常量來(lái)添加抄送和密送收件人。
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class RecipientTypesExample {
public static void main(String[] args) {
// 設(shè)置郵件服務(wù)器屬性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
// 創(chuàng)建會(huì)話對(duì)象
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@example.com", "your_password");
}
});
try {
// 創(chuàng)建郵件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@example.com"));
// 添加主要收件人(TO)
Address[] toRecipients = {new InternetAddress("recipient1@example.com")};
message.setRecipients(Message.RecipientType.TO, toRecipients);
// 添加抄送(CC)
Address[] ccRecipients = {new InternetAddress("cc_recipient@example.com")};
message.setRecipients(Message.RecipientType.CC, ccRecipients);
// 添加密送(BCC)
Address[] bccRecipients = {new InternetAddress("bcc_recipient@example.com")};
message.setRecipients(Message.RecipientType.BCC, bccRecipients);
message.setSubject("測(cè)試郵件收件人類型");
message.setText("這是一封測(cè)試郵件,演示不同的收件人類型。");
// 發(fā)送郵件
Transport.send(message);
System.out.println("郵件發(fā)送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
③發(fā)送一封emil給多個(gè)收件人,那么使用下面的方法來(lái)指定多個(gè)收件人ID:
void addRecipients(Message.RecipientType type,Address[] addresses) throws MessagingException
下面的是具體的代碼:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SecureEmailSender {
public static void main(String[] args) {
// 設(shè)置郵件服務(wù)器屬性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com"); // 設(shè)置郵件服務(wù)器主機(jī)名
properties.put("mail.smtp.port", "465"); // 設(shè)置郵件服務(wù)器端口號(hào)
properties.put("mail.smtp.auth", "true"); // 啟用身份驗(yàn)證
properties.put("mail.smtp.socketFactory.port", "465"); // 設(shè)置 SSL 端口
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 設(shè)置 SSL Socket Factory
properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退
// 創(chuàng)建會(huì)話對(duì)象
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@example.com", "your_password");
// 在這里填寫發(fā)送郵件的郵箱地址和密碼
}
});
try {
// 創(chuàng)建郵件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@example.com")); // 設(shè)置發(fā)件人郵箱
// 設(shè)置多個(gè)收件人郵箱
String[] recipients = {"recipient1@example.com", "recipient2@example.com"};
Address[] recipientAddresses = new Address[recipients.length];
for (int i = 0; i < recipients.length; i++) {
recipientAddresses[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, recipientAddresses);
message.setSubject("JavaMail API測(cè)試 - SSL加密"); // 設(shè)置郵件主題
message.setText("這是一封經(jīng)過(guò)SSL加密的測(cè)試郵件,發(fā)送給多個(gè)收件人。"); // 設(shè)置郵件內(nèi)容
// 發(fā)送郵件
Transport.send(message);
System.out.println("郵件發(fā)送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
④發(fā)送一封HTML E-mail如下:
package main.mail郵件Api;
// 文件名 SendHTMLEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendHTMLEmail
{
public static void main(String [] args)
{
// 收件人電子郵箱
String to = "Stevedash@qq.com";
// 發(fā)件人電子郵箱
String from = "Stevedash@qq.com";
// 指定發(fā)送郵件的主機(jī)為 localhost
String host = "smtp.qq.com";
// 獲取系統(tǒng)屬性
Properties properties = System.getProperties();
// 設(shè)置郵件服務(wù)器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
// 獲取默認(rèn)session對(duì)象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("Stevedash@qq.com", "dsadasdasdasda"); //發(fā)件人郵件用戶名、授權(quán)碼
}
});
try{
// 創(chuàng)建默認(rèn)的 MimeMessage 對(duì)象。
MimeMessage message = new MimeMessage(session);
// Set From: 頭部頭字段
message.setFrom(new InternetAddress(from));
// Set To: 頭部頭字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 頭字段/標(biāo)題頭
message.setSubject("This is the Subject Line!");
// 發(fā)送 HTML 消息, 可以插入html標(biāo)簽,就是展示出來(lái)是頁(yè)面中的同一個(gè)效果
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// 發(fā)送消息
Transport.send(message);
System.out.println("Sent message successfully....帶網(wǎng)頁(yè)標(biāo)簽效果的");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
如下圖:
⑤發(fā)送帶附件的郵件:
package main.mail郵件Api;
// 文件名 SendFileEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendFileEmail
{
public static void main(String [] args)
{
// 收件人電子郵箱
String to = "1207036895@qq.com";
// 發(fā)件人電子郵箱
String from = "1207036895@qq.com";
// 指定發(fā)送郵件的主機(jī)為 localhost
String host = "smtp.qq.com";
// 獲取系統(tǒng)屬性
Properties properties = System.getProperties();
// 設(shè)置郵件服務(wù)器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
// 獲取默認(rèn)session對(duì)象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("1207036895@qq.com", "zzzzzzzzzzzzzzzzzzz"); //發(fā)件人郵件用戶名、授權(quán)碼
}
});
try{
// 創(chuàng)建默認(rèn)的 MimeMessage 對(duì)象。
MimeMessage message = new MimeMessage(session);
// Set From: 頭部頭字段
message.setFrom(new InternetAddress(from));
// Set To: 頭部頭字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 頭字段
message.setSubject("This is the Subject Line!");
// 創(chuàng)建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText("This is message body");
// 創(chuàng)建多重消息
Multipart multipart = new MimeMultipart();
// 設(shè)置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
String filename = "D:/桌面/新建文本文檔.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// 發(fā)送完整消息
message.setContent(multipart );
// 發(fā)送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
可以發(fā)現(xiàn)有文件名出現(xiàn)亂碼,
下面修改后的代碼,解決了編碼的問(wèn)題
package main.mail郵件Api;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendFileEmail1 {
public static void main(String[] args) {
String to = "1207036895@qq.com";
String from = "1207036895@qq.com";
String host = "smtp.qq.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("1207036895@qq.com", "zzzzzzzzzzzzzzzzzzz");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("這是郵件主題"); // 設(shè)置郵件主題,這里使用中文
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("這是郵件正文內(nèi)容"); // 設(shè)置郵件正文內(nèi)容,這里使用中文
MimeBodyPart attachmentPart = new MimeBodyPart();
String filename = "D:/桌面/新建文本文檔.txt";
DataSource source = new FileDataSource(filename);
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(MimeUtility.encodeText(source.getName())); // 設(shè)置附件文件名,對(duì)文件名進(jìn)行編碼
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("郵件發(fā)送成功!");
} catch (MessagingException | UnsupportedEncodingException mex) {
mex.printStackTrace();
}
}
}
輸出結(jié)果如下:
注意事項(xiàng)和進(jìn)階功能
- 要保護(hù)郵箱安全,建議將密碼和敏感信息存儲(chǔ)在安全的方式中,如配置文件或環(huán)境變量。
- JavaMail API還支持更多高級(jí)功能,如附件、HTML內(nèi)容、抄送、密送等。您可以根據(jù)需要進(jìn)行擴(kuò)展。
- 為了避免被郵件服務(wù)器標(biāo)記為垃圾郵件,確保郵件內(nèi)容和行為遵循電子郵件的最佳實(shí)踐。
總結(jié)
? JavaMail API為Java程序員提供了發(fā)送電子郵件的便捷途徑。通過(guò)設(shè)置郵件服務(wù)器屬性、創(chuàng)建會(huì)話對(duì)象以及構(gòu)建郵件消息,我們可以輕松地在Java應(yīng)用程序中實(shí)現(xiàn)電子郵件發(fā)送功能。在實(shí)際項(xiàng)目中您可以根據(jù)不同場(chǎng)景的不同需求,采用如附件、HTML內(nèi)容和抄送等應(yīng)對(duì)。
作者:Stevedash
發(fā)表于:2023年8月13日 15點(diǎn)48分
來(lái)源:Java 發(fā)送郵件 | 菜鳥(niǎo)教程 (runoob.com)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-645962.html
注:本文內(nèi)容基于個(gè)人學(xué)習(xí)理解,如有錯(cuò)誤或疏漏,歡迎指正。感謝閱讀!如果覺(jué)得有幫助,請(qǐng)點(diǎn)贊和分享。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-645962.html
到了這里,關(guān)于一篇文章帶你了解Java發(fā)送郵件:使用JavaMail API發(fā)送電子郵件的注意事項(xiàng)、發(fā)送附件等的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!