javamail參考
package com.sai.mail;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class SendEmail {
public interface Callback {
void success(String s);
void error(String s, Exception e);
}
private Callback callback; //資訊回撥介面
private Properties properties;//系統屬性物件
private String mailAccount; //傳送郵箱地址
private String mailPassword; //驗證密碼
private Session session; //郵件會話物件
private String myNickName; //暱稱,傳送時自己的暱稱
private boolean debug = false;//debug模式
private boolean isSaveEmail = false;
private String pathName = "exc.eml";//郵件儲存時的
public SendEmail(String mailAccount, String mailPassword) {
this.mailAccount = mailAccount;
this.mailPassword = mailPassword;
}
public SendEmail setSaveEmail(String pathName) {
isSaveEmail = true;
this.pathName = pathName;
return this;
}
private List<String> recipientT0List = new ArrayList<>();//收件地址
private List<String> recipientCCList = new ArrayList<>();//密送地址
private List<String> recipientBCCList = new ArrayList<>();//抄送地址
private List<String> filePath = new ArrayList<>();//附件
public SendEmail setDebug(boolean sessionDebug) {
debug = sessionDebug;
return this;
}
/*** 設定多人收件人地址 */
public SendEmail addRecipientT0(String address) {
recipientT0List.add(address);
return this;
}
public SendEmail addRecipientCC(String address) {
recipientCCList.add(address);
return this;
}
public SendEmail addRecipientBCC(String address) {
recipientBCCList.add(address);
return this;
}
public SendEmail addRecipientT0(List<String> address) {
recipientT0List.addAll(address);
return this;
}
public SendEmail addRecipientCC(List<String> address) {
recipientCCList.addAll(address);
return this;
}
public SendEmail addRecipientBCC(List<String> address) {
recipientBCCList.addAll(address);
return this;
}
/***新增檔案***/
public SendEmail addFile(String filePath) {
this.filePath.add(filePath);
return this;
}
public SendEmail addFile(List<String> list) {
this.filePath.addAll(list);
return this;
}
/****暱稱設定**/
public SendEmail setMyNickName(String name) {
myNickName = name;
return this;
}
private MimeMessage message;
/**
* @param title 主題
* @param datas 內容
* @param type 內容格式型別 text/html;charset=utf-8
* @return s
*/
public SendEmail createMail(String title, String datas, String type) {
if (mailAccount.length() == 0 || mailAccount.equals(null)) {
System.err.println("發件地址不存在!");
return this;
}
if (myNickName == null) {
myNickName = mailAccount;
}
getProperties();
if (!sync) return this;
try {
message = new MimeMessage(session);
// 設定傳送郵件地址,param1 代表傳送地址 param2 代表傳送的名稱(任意的) param3 代表名稱編碼方式
message.setFrom(new InternetAddress(mailAccount, myNickName, "utf-8"));
setRecipientT0(); //新增接收人地址
setRecipientCC(); //新增抄送接收人地址
setRecipientBCC(); //新增密送接收人地址
BodyPart messageBodyPart = new MimeBodyPart(); // 建立訊息部分
Multipart multipart = new MimeMultipart(); // 建立多重訊息
messageBodyPart.setContent(datas, type); // 訊息內容
multipart.addBodyPart(messageBodyPart); // 設定文字訊息部分
addFile(multipart); //附件部分
// 傳送完整訊息
message.setContent(multipart);
message.setSubject(title); // 設定郵件主題
message.setSentDate(new Date()); // 設定傳送時間
message.saveChanges(); // 儲存上面的編輯內容
// 將上面建立的物件寫入本地
saveEmail(title);
} catch (Exception e) {
if (callback != null)
callback.error("message error ", e);
sync = false;
}
return this;
}
public void sendEmail(Callback callback) {
this.callback = callback;
if (!sync)
return;
try {
Transport trans = session.getTransport();
// 連結郵件伺服器
trans.connect(mailAccount, mailPassword);
// 傳送資訊
trans.sendMessage(message, message.getAllRecipients());
// 關閉連結
trans.close();
if (callback != null)
callback.success("傳送完成");
} catch (Exception e) {
if (callback != null)
callback.error("傳送異常", e);
}
}
private void saveEmail(String title) throws IOException, MessagingException {
OutputStream out = null;
if (isSaveEmail) {
if (pathName.length() == 0 || pathName.equals(null)) {
out = new FileOutputStream(title + ".eml");
} else {
String path[] = pathName.split("\\.");
out = new FileOutputStream(path[0] + title + ".eml");
}
}
message.writeTo(out);
out.flush();
out.close();
}
/*** 設定收件人地址資訊*/
private void setRecipientT0() throws MessagingException, UnsupportedEncodingException {
if (recipientT0List.size() > 0) {
InternetAddress[] sendTo = new InternetAddress[recipientT0List.size()];
for (int i = 0; i < recipientT0List.size(); i++) {
System.out.println("傳送到:" + recipientT0List.get(i));
sendTo[i] = new InternetAddress(recipientT0List.get(i), "", "UTF-8");
}
message.addRecipients(MimeMessage.RecipientType.TO, sendTo);
}
}
/***設定密送地址**/
private void setRecipientCC() throws MessagingException, UnsupportedEncodingException {
if (recipientCCList.size() > 0) {
InternetAddress[] sendTo = new InternetAddress[recipientCCList.size()];
for (int i = 0; i < recipientCCList.size(); i++) {
System.out.println("傳送到:" + recipientCCList.get(i));
sendTo[i] = new InternetAddress(recipientCCList.get(i), "", "UTF-8");
}
message.addRecipients(MimeMessage.RecipientType.CC, sendTo);
}
}
/***設定抄送郵件地址**/
private void setRecipientBCC() throws MessagingException, UnsupportedEncodingException {
if (recipientBCCList.size() > 0) {
InternetAddress[] sendTo = new InternetAddress[recipientBCCList.size()];
for (int i = 0; i < recipientBCCList.size(); i++) {
System.out.println("傳送到:" + recipientBCCList.get(i));
sendTo[i] = new InternetAddress(recipientBCCList.get(i), "", "UTF-8");
}
message.addRecipients(MimeMessage.RecipientType.BCC, sendTo);
}
}
/***新增附件****/
private void addFile(Multipart multipart) throws MessagingException, UnsupportedEncodingException {
if (filePath.size() == 0)
return;
for (int i = 0; i < filePath.size(); i++) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
// 選擇出每一個附件名
String pathName = filePath.get(i);
System.out.println("新增附件 ====>" + pathName);
// 得到資料來源
FileDataSource fds = new FileDataSource(pathName);
// 得到附件本身並至入BodyPart
messageBodyPart.setDataHandler(new DataHandler(fds));
//採用這去除中文亂碼
messageBodyPart.setFileName(MimeUtility.encodeText(fds.getName()));
multipart.addBodyPart(messageBodyPart);
}
}
private boolean sync = true;
/**
* 規定設定 傳輸協議為smtp 根據輸入的郵箱地址自動匹配smtp伺服器地址與smtp伺服器地址埠
*/
private void getProperties() {
String account[] = mailAccount.split("@");
String mailTpye = "";
try {
mailTpye = account[1];
} catch (Exception e) {
System.err.println("不正確的郵箱地址!");
sync = false;
return;
}
String SMTPHost = "";//smtp伺服器地址
String SMTPPort = "";//smtp伺服器地址埠
switch (mailTpye) {
case "qq.com":
case "foxmail.com":
SMTPHost = "smtp.qq.com";
SMTPPort = "465";
break;
case "sina.com":
SMTPHost = "smtp.sina.com";
SMTPPort = "25";
break;
case "sina.cn":
SMTPHost = "smtp.sina.cn";
SMTPPort = "25";
break;
case "139.com":
SMTPHost = "smtp.139.com";
SMTPPort = "465";
break;
case "163.com":
SMTPHost = "smtp.163.com";
SMTPPort = "25";
break;
case "188.com":
SMTPHost = "smtp.188.com";
SMTPPort = "25";
break;
case "126.com":
SMTPHost = "smtp.126.com";
SMTPPort = "25";
break;
case "gmail.com":
SMTPHost = "smtp.gmail.com";
SMTPPort = "465";
break;
case "outlook.com":
SMTPHost = "smtp.outlook.com";
SMTPPort = "465";
break;
default:
System.err.println("暫時不支援此賬號作為服務賬號傳送郵件!");
return;
}
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp"); // 設定郵件傳輸採用的協議smtp
prop.setProperty("mail.smtp.host", SMTPHost);// 設定傳送人郵件伺服器的smtp地址
prop.setProperty("mail.smtp.auth", "true"); // 設定驗證機制
prop.setProperty("mail.smtp.port", SMTPPort);// SMTP 伺服器的埠 (非 SSL 連線的埠一般預設為 25, 可以不新增, 如果開啟了 SSL 連線,
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.port", SMTPPort);
properties = prop;
session = Session.getInstance(properties);
session.setDebug(debug);
}
}
相關文章
- OSI參考模型和TCP/IP參考模型模型TCP
- SQLAlchemy參考SQL
- 參考地址
- DOM參考手冊及事件參考手冊事件
- WebApiClient效能參考WebAPIclient
- OSI參考模型模型
- Git教程參考Git
- 參考資料
- 前端參考指南前端
- SRVCTL 命令參考
- XMLHTTP物件參考XMLHTTP物件
- 模擬考試參考程式碼
- CloudBeaver 參考架構Cloud架構
- Blender參考API用法API
- SQL優化參考SQL優化
- Oracle ASMCMD命令參考OracleASM
- MarkDown語法參考
- mybatis學習參考MyBatis
- [ CSS ] animation 快速參考CSS
- #region(C# 參考)C#
- RAC安裝 參考
- QThread類參考QTthread
- aix 參考資料AI
- Oracle常用Event參考Oracle
- sql 優化參考SQL優化
- oracle 參考資料Oracle
- PyQtGraph繪圖參考QT繪圖
- C語言考試大綱(參考)C語言
- javamailJavaAI
- multipath配置詳細參考
- mysql許可權參考MySql
- docker 安裝 MySQL (參考)DockerMySql
- JavaScript Math(數學) 參考JavaScript
- em字型大小參考物件物件
- JavaScript物件參考手冊JavaScript物件
- HTML標籤參考(一)HTML
- Elasticsearch 參考指南(介紹)Elasticsearch
- OSI七層參考模型模型