更新時(shí)間:2022-05-18 11:00:07 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1794次
使用Java應(yīng)用程序發(fā)送 E-mail 十分簡(jiǎn)單,但是首先你應(yīng)該在你的機(jī)器上安裝 JavaMail API 和Java Activation Framework (JAF) 。
您可以從 Java 網(wǎng)站下載最新版本的 JavaMail,打開網(wǎng)頁(yè)右側(cè)有個(gè) Downloads 鏈接,點(diǎn)擊它下載。
您可以從 Java 網(wǎng)站下載最新版本的 JAF(版本 1.1.1)。
你也可以使用本站提供的下載鏈接:
JavaMail mail.jar 1.4.5
JAF(版本 1.1.1) activation.jar
下載并解壓縮這些文件,在新創(chuàng)建的頂層目錄中,您會(huì)發(fā)現(xiàn)這兩個(gè)應(yīng)用程序的一些 jar 文件。您需要把 mail.jar 和 activation.jar文件添加到您的 CLASSPATH 中。
如果你使用第三方郵件服務(wù)器如QQ的SMTP服務(wù)器,可查看文章底部用戶認(rèn)證完整的實(shí)例。
下面是一個(gè)發(fā)送簡(jiǎn)單E-mail的例子。假設(shè)你的localhost已經(jīng)連接到網(wǎng)絡(luò)。
如果需要提供用戶名和密碼給e-mail服務(wù)器來達(dá)到用戶認(rèn)證的目的,你可以通過如下設(shè)置來完成:
props.put("mail.smtp.auth", "true");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
需要用戶名密碼驗(yàn)證郵件發(fā)送實(shí)例:
你需要在登錄QQ郵箱后臺(tái)在"設(shè)置"=》賬號(hào)中開啟POP3/SMTP服務(wù) ,如下圖所示:
這里已經(jīng)開啟了。需要生成授權(quán)碼,仔細(xì)看說明就行。生成授權(quán)碼后會(huì)給你一串字符,它是密碼
SendEmail2.java
// 需要用戶名密碼郵件發(fā)送實(shí)例
//文件名 SendEmail2.java
//本實(shí)例以QQ郵箱為例,你需要在qq后臺(tái)設(shè)置
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail2
{
public static void main(String [] args)
{
// 收件人電子郵箱
String to = "xxx@qq.com";
// 發(fā)件人電子郵箱
String from = "xxx@qq.com";
// 指定發(fā)送郵件的主機(jī)為 smtp.qq.com
String host = "smtp.qq.com"; //QQ 郵件服務(wù)器
// 獲取系統(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("xxx@qq.com", "qq郵箱密碼"); //發(fā)件人郵件用戶名、密碼
}
});
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!");
// 設(shè)置消息體
message.setText("This is actual message");
// 發(fā)送消息
Transport.send(message);
System.out.println("Sent message successfully....from runoob.com");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
實(shí)體類
MailEntity .java
package com.fantj.myEmail;
/**
* 郵件實(shí)體類
* Created by Fant.J.
*/
@Data
public class MailEntity implements Serializable {
//此處填寫SMTP服務(wù)器
private String smtpService;
//設(shè)置端口號(hào)
private String smtpPort;
//設(shè)置發(fā)送郵箱
private String fromMailAddress;
// 設(shè)置發(fā)送郵箱的STMP口令
private String fromMailStmpPwd;
//設(shè)置郵件標(biāo)題
private String title;
//設(shè)置郵件內(nèi)容
private String content;
//內(nèi)容格式(默認(rèn)采用html)
private String contentType;
//接受郵件地址集合
private List<String> list = new ArrayList<>();
}
enum 類
MailContentTypeEnum .java
package com.fantj.myEmail.emailEnum;
/**
* 自定義的枚舉類型,枚舉類型包含了郵件內(nèi)容的類型
* Created by Fant.J.
*/
public enum MailContentTypeEnum {
HTML("text/html;charset=UTF-8"), //html格式
TEXT("text")
;
private String value;
MailContentTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
package com.fantj.myEmail.emailEnum;
/**
* 自定義的枚舉類型,枚舉類型包含了郵件內(nèi)容的類型
* Created by Fant.J.
*/
public enum MailContentTypeEnum {
HTML("text/html;charset=UTF-8"), //html格式
TEXT("text")
;
private String value;
MailContentTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
郵件發(fā)送類
MailSender .java
package com.fantj.myEmail;
/**
* 郵件發(fā)送類
* Created by Fant.J.
*/
public class MailSender {
//郵件實(shí)體
private static MailEntity mail = new MailEntity();
/**
* 設(shè)置郵件標(biāo)題
* @param title 標(biāo)題信息
* @return
*/
public MailSender title(String title){
mail.setTitle(title);
return this;
}
/**
* 設(shè)置郵件內(nèi)容
* @param content
* @return
*/
public MailSender content(String content)
{
mail.setContent(content);
return this;
}
/**
* 設(shè)置郵件格式
* @param typeEnum
* @return
*/
public MailSender contentType(MailContentTypeEnum typeEnum)
{
mail.setContentType(typeEnum.getValue());
return this;
}
/**
* 設(shè)置請(qǐng)求目標(biāo)郵件地址
* @param targets
* @return
*/
public MailSender targets(List<String> targets)
{
mail.setList(targets);
return this;
}
/**
* 執(zhí)行發(fā)送郵件
* @throws Exception 如果發(fā)送失敗會(huì)拋出異常信息
*/
public void send() throws Exception
{
//默認(rèn)使用html內(nèi)容發(fā)送
if(mail.getContentType() == null) {
mail.setContentType(MailContentTypeEnum.HTML.getValue());
}
if(mail.getTitle() == null || mail.getTitle().trim().length() == 0)
{
throw new Exception("郵件標(biāo)題沒有設(shè)置.調(diào)用title方法設(shè)置");
}
if(mail.getContent() == null || mail.getContent().trim().length() == 0)
{
throw new Exception("郵件內(nèi)容沒有設(shè)置.調(diào)用content方法設(shè)置");
}
if(mail.getList().size() == 0)
{
throw new Exception("沒有接受者郵箱地址.調(diào)用targets方法設(shè)置");
}
//讀取/resource/mail_zh_CN.properties文件內(nèi)容
final PropertiesUtil properties = new PropertiesUtil("mail");
// 創(chuàng)建Properties 類用于記錄郵箱的一些屬性
final Properties props = new Properties();
// 表示SMTP發(fā)送郵件,必須進(jìn)行身份驗(yàn)證
props.put("mail.smtp.auth", "true");
//此處填寫SMTP服務(wù)器
props.put("mail.smtp.host", properties.getValue("mail.smtp.service"));
//設(shè)置端口號(hào),QQ郵箱給出了兩個(gè)端口465/587
props.put("mail.smtp.port", properties.getValue("mail.smtp.prot"));
// 設(shè)置發(fā)送郵箱
props.put("mail.user", properties.getValue("mail.from.address"));
// 設(shè)置發(fā)送郵箱的16位STMP口令
props.put("mail.password", properties.getValue("mail.from.smtp.pwd"));
// 構(gòu)建授權(quán)信息,用于進(jìn)行SMTP進(jìn)行身份驗(yàn)證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用環(huán)境屬性和授權(quán)信息,創(chuàng)建郵件會(huì)話
Session mailSession = Session.getInstance(props, authenticator);
// 創(chuàng)建郵件消息
MimeMessage message = new MimeMessage(mailSession);
// 設(shè)置發(fā)件人
String nickName = MimeUtility.encodeText(properties.getValue("mail.from.nickname"));
InternetAddress form = new InternetAddress(nickName + " <" + props.getProperty("mail.user") + ">");
message.setFrom(form);
// 設(shè)置郵件標(biāo)題
message.setSubject(mail.getTitle());
//html發(fā)送郵件
if(mail.getContentType().equals(MailContentTypeEnum.HTML.getValue())) {
// 設(shè)置郵件的內(nèi)容體
message.setContent(mail.getContent(), mail.getContentType());
}
//文本發(fā)送郵件
else if(mail.getContentType().equals(MailContentTypeEnum.TEXT.getValue())){
message.setText(mail.getContent());
}
//發(fā)送郵箱地址
List<String> targets = mail.getList();
for(int i = 0;i < targets.size();i++){
try {
// 設(shè)置收件人的郵箱
InternetAddress to = new InternetAddress(targets.get(i));
message.setRecipient(Message.RecipientType.TO, to);
// 最后當(dāng)然就是發(fā)送郵件啦
Transport.send(message);
}catch (Exception e)
{
continue;
}
}
}
}
配置文件的讀取工具類
PropertiesUtil .java
package com.fantj.myEmail;
/**
* PropertiesUtil是用于讀取*.properties配置文件的工具類
* Created by Fant.J.
*/
public class PropertiesUtil {
private final ResourceBundle resource;
private final String fileName;
/**
* 構(gòu)造函數(shù)實(shí)例化部分對(duì)象,獲取文件資源對(duì)象
*
* @param fileName
*/
public PropertiesUtil(String fileName)
{
this.fileName = fileName;
this.resource = ResourceBundle.getBundle(this.fileName, Locale.SIMPLIFIED_CHINESE);
}
/**
* 根據(jù)傳入的key獲取對(duì)象的值 getValue
*
* @param key properties文件對(duì)應(yīng)的key
* @return String 解析后的對(duì)應(yīng)key的值
*/
public String getValue(String key)
{
String message = this.resource.getString(key);
return message;
}
/**
* 獲取properties文件內(nèi)的所有key值<br>
* @return
*/
public Enumeration<String> getKeys(){
return resource.getKeys();
}
}
配置文件
mail.properties
mail.smtp.service=smtp.qq.com
mail.smtp.prot=587
mail.from.address=844072586@qq.com
mail.from.smtp.pwd=這里填寫自己的授權(quán)碼
mail.from.nickname=這里填寫 將名字轉(zhuǎn)換成ascii碼放在這里
測(cè)試類
MailTest .java
package com.fantj.myEmail;
/**
* Created by Fant.J.
*/
public class MailTest {
@Test
public void test() throws Exception {
for (int i = 0;i<20;i++){
new MailSender()
.title("焦哥給你發(fā)送的郵件")
.content("你就是傻")
.contentType(MailContentTypeEnum.TEXT)
.targets(new ArrayList<String>(){{
add("xxxxx@qq.com");
}})
.send();
Thread.sleep(1000);
System.out.println("第"+i+"次發(fā)送成功!");
}
}
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)