java 郵件發送


<!-- 郵件發送 -->
<dependency >  
   <groupId >javax.mail </groupId >  
   <artifactId >mail </artifactId >  
   <version >1.4.5 </version >  
</dependency >  

<dependency >  
   <groupId >com.sun.mail </groupId >  
   <artifactId >javax.mail </artifactId >  
   <version >1.5.4 </version >  
</dependency > 








package com.dt.util;

 /**
 *@author dt
 *@date 2018年1月9日 下午2:43:08
 *@marker
 */
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class MailUtils {


/**
* 郵件服務器地址
*/
private String host = "smtp.163.com";
/**
* 發件人用戶名
*/
private String userName = "[email protected]";
/**
* 發件人密碼
*/
private String password = "520395";
/**
* 發件人暱稱
*/
private String nick = "";
/**
* 是否需要權限驗證
*/
private boolean auth = true;

/**
* 是否需要代理
*/
private boolean isProxy = false;
/**
* 代理服務器地址
*/
private String socksProxyHost;
/**
* 代理服務器端口
*/
private String socksProxyPort;



private MimeMessage message;


/**
* 構造函數一(使用默認發送設置)
*/
public MailUtils() {

}
/**
* 構造函數二(指定發送設置)
* @param host
* @param userName
* @param password
*/
public MailUtils(String host, String userName, String password) {
this.host = host;
this.userName = userName;
this.password = password;
}
/**
* 構造函數三(指定發送設置)

* @param host
* @param userName
* @param password
* @param nick
* @param auth
*/
public MailUtils(String host, String userName, String password,
String nick, boolean auth) {
this.host = host;
this.userName = userName;
this.password = password;
this.nick = nick;
this.auth = auth;
}
/**
* 設置郵件代理服務器
* @param socksProxyHost
* @param socksProxyPort
*/
public void setProxy(String socksProxyHost, String socksProxyPort){
this.isProxy = true;
this.socksProxyHost = socksProxyHost;
this.socksProxyPort = socksProxyPort;
}
/**
* 發送郵件(構造方法一)
* @param to
* @param title
* @param content
* @return
*/
public boolean send(String[] to, String title, String content) {
return send(to, title, content, null);
}
/**
* 發送郵件(構造方法二)
* @param to
* @param title
* @param content
* @param filePath
* @return
*/
public boolean send(String[] to, String title, String content, String[] filePath) {
boolean result = false;


try {
// 郵件發送設置(郵件服務器、發件人)
setMailInfo();

// 設置郵件標題
message.setSubject(title);

// 設置郵件內容體
message.setContent(getContent(content,filePath));

// 設置接收者(多個接收者)
Address[] address = new Address[to.length];
for (int i = 0; i < to.length; i++) {
address[i] = new InternetAddress(to[i]);
}
/* 正常(Message.RecipientType.TO)
* 抄送(Message.RecipientType.CC)
* 密送(Message.RecipientType.BCC)
*/
message.addRecipients(Message.RecipientType.TO, address);


// 發送郵件
Transport.send(message);


result = true;
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}


return result;
}

/**
* 郵件發送設置(郵件服務器、發件人)

* @throws AddressException
* @throws MessagingException
*/
private void setMailInfo() throws AddressException, MessagingException {
Properties props = new Properties();
if(this.isProxy){
props.setProperty("proxySet", "true");
props.setProperty("socksProxyHost", this.socksProxyHost);
       props.setProperty("socksProxyPort", this.socksProxyPort);
}
        
// 郵件服務器地址
props.put("mail.smtp.host", this.host);
// 發件人賬號
props.put("mail.user", this.userName);
// 發件人密碼
props.put("mail.password", this.password);
// 是否需要身份驗證
props.put("mail.smtp.auth", auth ? "true" : "false");


// 創建Session實例
Session session = null;
if (auth) {
// 構建授權信息,進行SMTP身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
session = Session.getDefaultInstance(props, authenticator);
} else {
session = Session.getDefaultInstance(props);
}


// 創建郵件消息
message = new MimeMessage(session);


// 設置發件人
if (nick != null && !nick.equals("")) { // 如果暱稱不爲空,則設置暱稱
// 設置暱稱
try {
nick = MimeUtility.encodeText(nick);
message.setFrom(new InternetAddress(nick + " <" + this.userName + ">"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// 設置發件人
message.setFrom(new InternetAddress(this.userName));
}

// 設置發送日期
message.setSentDate(new Date());
}

/**
* 構造郵件內容體
* @param content
* @param filePath
* @return
* @throws MessagingException
*/
private MimeMultipart getContent(String content, String[] filePath) throws MessagingException{
// 構造郵件內容體
MimeMultipart mmp = new MimeMultipart();
// 設置郵件的內容體
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>" + content, "text/html;charset=UTF-8");
mmp.addBodyPart(bodyPart);

// 添加多個附件
if (filePath != null) {
FileDataSource fileds;
File file;
for (int i = 0; i < filePath.length; i++) {
bodyPart = new MimeBodyPart();
file = new File(filePath[i]);
if(!file.exists()){
continue;
}
fileds = new FileDataSource(file);
// 添加附件
bodyPart.setDataHandler(new DataHandler(fileds));
// 設置附件名稱
bodyPart.setFileName(fileds.getName());
// 把附件添加到 MimeMultipart
mmp.addBodyPart(bodyPart);
}
}

return mmp;
}

/**
* 基本的測試(郵件設置配置死的,實用過程中可以從配置文件中讀取)
*/
public static void test1 (){
/******************| 發送設置 |*****************/
// 實例化郵件發送工具類(有三個構造函數)
MailUtils mu = new MailUtils();

/******************| 郵件內容設置 |*****************/
// 1、設置收件人,必填項(數組,支持過個收件人)
String[] to = { "[email protected]","[email protected]" };
// 2、設置郵件標題,必填項
String title = "這是郵件標題";
// 3、設置郵件內容,必填項(支持HTML格式與普通文本)
String content = "這是郵件內容";
// 4、發送郵件
if (mu.send(to, title, content)) {
System.out.println("發送成功~");
} else {
System.out.println("發送失敗~");
}
}

/**
* 基本的測試(郵件設置配置死的,實用過程中可以從配置文件中讀取)
* 包含附件
*/
public static void test2 (){
/******************| 發送設置 |*****************/
// 實例化郵件發送工具類(有三個構造函數)
MailUtils mu = new MailUtils();

/******************| 郵件內容設置 |*****************/
// 1、設置收件人,必填項(數組,支持過個收件人)
String[] to = { "[email protected]","[email protected]"};
// 2、設置郵件標題,必填項
String title = "這是郵件標題";
// 3、設置郵件內容,必填項(支持HTML格式與普通文本)
String content = "這是郵件內容";
// 4、設置附件,選填項(數組,支持多附件)
String[] filePath = {"/Users/qmxl/1.jpg","/Users/qmxl/2.jpg"};
// 5、發送郵件
if (mu.send(to, title, content,filePath)) {
System.out.println("發送成功~");
} else {
System.out.println("發送失敗~");
}
}

/**
* 完整的郵件發送設置方法
*/
public static void test3 (){
/******************| 發送設置 |*****************/
// 郵件服務器地址
String host = "smtp.163.com";
// 發件人用戶名
String userName = "[email protected]";
// 發件人密碼
String password = "123456";
// 發件人暱稱
String nick = "XXX共享信息平臺";
// 是否需要權限驗證
boolean auth = true;
// 實例化郵件發送工具類(有三個構造函數)
MailUtils mu = new MailUtils(host, userName, password, nick, auth);

/******************| 設置代理 |*****************/
// 代理服務器地址
String socksProxyHost = "192.168.168.168";
// 代理服務器端口
String socksProxyPort = "1080";
mu.setProxy(socksProxyHost, socksProxyPort);


/******************| 郵件內容設置 |*****************/
// 1、設置收件人,必填項(數組,支持過個收件人)
String[] to = { "[email protected]","[email protected]" };
// 2、設置郵件標題,必填項
String title = "這是郵件標題";
// 3、設置郵件內容,必填項(支持HTML格式與普通文本)
String content = "這是郵件內容";
// 4、設置附件,選填項(數組,支持多附件)
String[] filePath = {"/Users/qmxl/1.jpg","/Users/qmxl/2.jpg"};
// 5、發送郵件
if (mu.send(to, title, content,filePath)) {
System.out.println("發送成功~");
} else {
System.out.println("發送失敗~");
}
}


public static void main(String[] args) {
MailUtils.test1();
//MailUtils.test2();
//MailUtils.test3();
}

}
發佈了153 篇原創文章 · 獲贊 19 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章