前文摘自 菜鳥教程 : http://www.runoob.com/java/java-sending-email.html
使用Java應用程式發送 E-mail 十分簡單,但是首先你應該在你的機器上安裝 JavaMail API 和Java Activation Framework (JAF) 。
- 您可以從 Java 網站下載下傳最新版本的 JavaMail ,打開網頁右側有個 Downloads 連結,點選它下載下傳。
- JAF(版本 1.1.1) 。
你也可以使用本站提供的下載下傳連結:
下載下傳并解壓縮這些檔案,在新建立的頂層目錄中,您會發現這兩個應用程式的一些 jar 檔案。您需要把 mail.jar 和 activation.jar檔案添加到您的 CLASSPATH 中。
如果你使用第三方郵件伺服器如QQ的SMTP伺服器,可檢視文章底部使用者認證完整的執行個體。
發送一封簡單的 E-mail
下面是一個發送簡單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+"次發送成功!");
}
}
}
ok了,自己動手試試吧。