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