發送郵件(帶附件)

背景html

最近項目中涉及到發送郵件功能,也參照了不少學習資料,現將Demo例子分享一下,看成記錄,也使更多人能更快使用.java

本篇不涉及原理內容,若是有須要,後續補充討論.服務器

 

所需jar包session

mail-1.4.jar學習

學習內容測試

發送郵件(帶附件)spa

進入正題.net

實現Java發送郵件的過程大致有如下幾步:debug

1. 準備一個properties文件,該文件用於存放SMTP服務器地址等參數。code

2. 利用properties建立一個Session對象

3. 利用Session建立Message對象,而後設置郵件主題,收件人及正文等信息

4. 利用Transport對象發送郵件

 

SHOW YOU MY CODE

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
public static void main(String[] args) throws Exception{
// 郵件主題
String subject = "郵件Demo";
// 文件存放路徑
String filePath ="e:\\test.txt";
//1. 用於存放 SMTP 服務器地址等參數
Properties properties = new Properties();
// 主機地址
properties.setProperty("mail.smtp.host", "主機地址");
// 郵件協議
properties.setProperty("mail.transport.protocol", "smtp");
// 認證
properties.setProperty("mail.smtp.auth", "true");
// 端口
properties.setProperty("mail.smtp.port", "25");
 
// 使用JavaMail發送郵件的5個步驟
// 2. 建立session
Session session = Session.getDefaultInstance(properties, new MyAuthenticator("發件人帳號", "發件人密碼"));
// 開啓Session的debug模式,這樣就能夠查看到程序發送Email的運行狀態
session.setDebug(true);
 
// 3. 建立郵件
// 建立郵件對象
MimeMessage message = new MimeMessage(session);
 
// 郵件的標題
message.setSubject(subject);
// 郵件發送日期
message.setSentDate(new Date());
// 指明郵件的發件人
message.setFrom(new InternetAddress("指明郵件發件人郵箱"));
 
// 指明郵件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人郵箱", "別名"));
 
// 指明郵件的抄送人
message.setRecipient(Message.RecipientType.CC, new InternetAddress("收件人郵箱", "別名"));
 
// 向multipart對象中添加郵件的各個部份內容,包括文本內容和附件
Multipart multipart = new MimeMultipart();
 
// 添加郵件正文
BodyPart contentBodyPart = new MimeBodyPart();
// 郵件內容
String result = "Hello World!";
contentBodyPart.setContent(result, "text/html;charset=UTF-8");
multipart.addBodyPart(contentBodyPart);
 
 
// 添加附件
if (filePath != null && !"".equals(filePath)) {
BodyPart attachmentBodyPart = new MimeBodyPart();
// 根據附件路徑獲取文件,
FileDataSource dataSource = new FileDataSource(filePath);
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
//MimeUtility.encodeWord能夠避免文件名亂碼
attachmentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 郵件的文本內容
message.setContent(multipart);
 
// 4. 發送郵件,Transport每次發送成功程序幫忙關閉
Transport.send(message, message.getAllRecipients());
}
 來自CODE的代碼片
發送郵件可帶附件.java
另外還有一個實體驗證類
 

最後查看效果圖:

示例中,須要在E盤下建立一個test.txt文本,測試的同窗請將郵箱地址配置成本身的郵箱,

後續補充內容

1.採用Freemarker 將郵件正文模板化

2.支持批量發送

相關文章
相關標籤/搜索