使用JavaMail簡單的發送郵件
一、JavaMail簡介
JavaMail,顧名思義,提供給開發者處理電子郵件相關的編程接口。它是Sun發佈的用來處理email的API。它可以方便地執行一些常用的郵件傳輸。
二、簡單使用
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
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.Multipart;
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 SendEmail {
private String username = null;
private String password = null;
private Authenticator auth = null;
private MimeMessage mimeMessage =null;
private Properties pros = null;
private Multipart multipart = null;
private BodyPart bodypart= null;
/**
* 初始化賬號密碼並驗證
* 創建MimeMessage對象
* 發送郵件必須的步驟:1
* @param username
* @param password
*/
public SendEmail(String username,String password){
this.username = username;
this.password = password;
}
/**
* 初始化MimeMessage對象
* 發送郵件必須的步驟:3
*/
public void initMessage(){
this.auth = new Email_Autherticator();
Session session = Session.getDefaultInstance(pros,auth);
session.setDebug(true); //設置獲取 debug 信息
mimeMessage = new MimeMessage(session);
}
/**
* 設置email系統參數
* 接收一個map集合key爲string類型,值爲String
* 發送郵件必須的步驟:2
* @param map
*/
public void setPros(Map<String,String> map){
pros = new Properties();
for(Map.Entry<String,String> entry:map.entrySet()){
pros.setProperty(entry.getKey(), entry.getValue());
}
}
/**
* 驗證賬號密碼
* 發送郵件必須的步驟
* @author Administrator
*
*/
public class Email_Autherticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
}
/**
* 設置發送郵件的基本參數(去除繁瑣的郵件設置)
* @param sub 設置郵件主題
* @param text 設置郵件文本內容
* @param rec 設置郵件接收人
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{
mimeMessage.setSubject(sub);
mimeMessage.setText(text);
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
mimeMessage.setSentDate(new Date());
mimeMessage.setFrom(new InternetAddress(username,username));
}
/**
* 設置主題
* @param subject
* @throws MessagingException
*/
public void setSubject(String subject) throws MessagingException{
mimeMessage.setSubject(subject);
}
/**
* 設置日期
* @param date
* @throws MessagingException
*/
public void setDate(Date date) throws MessagingException{
mimeMessage.setSentDate(new Date());
}
/**
* 設置郵件文本內容
* @param text
* @throws MessagingException
*/
public void setText(String text) throws MessagingException{
mimeMessage.setText(text);
}
/**
* 設置郵件頭部
* @param arg0
* @param arg1
* @throws MessagingException
*/
public void setHeader(String arg0,String arg1) throws MessagingException{
mimeMessage.setHeader(arg0, arg1);
}
/**
* 設置郵件接收人地址 <單人發送>
* @param recipient
* @throws MessagingException
*/
public void setRecipient(String recipient) throws MessagingException{
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
/**
* 設置郵件接收人地址 <多人發送>
* @param list
* @throws MessagingException
* @throws AddressException
*/
public String setRecipients(List<String> recs) throws AddressException, MessagingException{
if(recs.isEmpty()){
return "接收人地址爲空!";
}
for(String str:recs){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
return "加入接收人地址成功!";
}
/**
* 設置郵件接收人地址 <多人發送>
* @param StringBuffer<parms,parms2,parms.....>
* @throws MessagingException
* @throws AddressException
*/
@SuppressWarnings("static-access")
public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{
if(sb==null||"".equals(sb)){
return "字符串數據爲空!";
}
Address []address = new InternetAddress().parse(sb.toString());
mimeMessage.addRecipients(Message.RecipientType.TO, address);
return "收件人加入成功";
}
/**
* 設置郵件發送人的名字
* @param from
* @throws UnsupportedEncodingException
* @throws MessagingException
*/
public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{
mimeMessage.setFrom(new InternetAddress(username,from));
}
/**
* 發送郵件<單人發送>
* return 是否發送成功
* @throws MessagingException
*/
public String sendMessage() throws MessagingException{
Transport.send(mimeMessage);
return "success";
}
/**
* 設置附件
* @param file 發送文件的路徑
*/
public void setMultipart(String file) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
multipart.addBodyPart(writeFiles(file));
mimeMessage.setContent(multipart);
}
/**
* 設置附件<添加多附件>
* @param fileList<接收List集合>
* @throws MessagingException
* @throws IOException
*/
public void setMultiparts(List<String> fileList) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
for(String s:fileList){
multipart.addBodyPart(writeFiles(s));
}
mimeMessage.setContent(multipart);
}
/**
* 發送文本內容,設置編碼方式
* <方法與發送附件配套使用>
* <發送普通的文本內容請使用setText()方法>
* @param s
* @param type
* @throws MessagingException
*/
public void setContent(String s,String type) throws MessagingException{
if(multipart==null){
multipart = new MimeMultipart();
}
bodypart = new MimeBodyPart();
bodypart.setContent(s, type);
multipart.addBodyPart(bodypart);
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
}
/**
* 讀取附件
* @param filePath
* @return
* @throws IOException
* @throws MessagingException
*/
public BodyPart writeFiles(String filePath)throws IOException, MessagingException{
File file = new File(filePath);
if(!file.exists()){
throw new IOException("文件不存在!請確定文件路徑是否正確");
}
bodypart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(dataSource));
//文件名要加入編碼,不然出現亂碼
bodypart.setFileName(MimeUtility.encodeText(file.getName()));
return bodypart;
}
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
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.Multipart;
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 SendEmail {
private String username = null;
private String password = null;
private Authenticator auth = null;
private MimeMessage mimeMessage =null;
private Properties pros = null;
private Multipart multipart = null;
private BodyPart bodypart= null;
/**
* 初始化賬號密碼並驗證
* 創建MimeMessage對象
* 發送郵件必須的步驟:1
* @param username
* @param password
*/
public SendEmail(String username,String password){
this.username = username;
this.password = password;
}
/**
* 初始化MimeMessage對象
* 發送郵件必須的步驟:3
*/
public void initMessage(){
this.auth = new Email_Autherticator();
Session session = Session.getDefaultInstance(pros,auth);
session.setDebug(true); //設置獲取 debug 信息
mimeMessage = new MimeMessage(session);
}
/**
* 設置email系統參數
* 接收一個map集合key爲string類型,值爲String
* 發送郵件必須的步驟:2
* @param map
*/
public void setPros(Map<String,String> map){
pros = new Properties();
for(Map.Entry<String,String> entry:map.entrySet()){
pros.setProperty(entry.getKey(), entry.getValue());
}
}
/**
* 驗證賬號密碼
* 發送郵件必須的步驟
* @author Administrator
*
*/
public class Email_Autherticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
}
/**
* 設置發送郵件的基本參數(去除繁瑣的郵件設置)
* @param sub 設置郵件主題
* @param text 設置郵件文本內容
* @param rec 設置郵件接收人
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{
mimeMessage.setSubject(sub);
mimeMessage.setText(text);
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
mimeMessage.setSentDate(new Date());
mimeMessage.setFrom(new InternetAddress(username,username));
}
/**
* 設置主題
* @param subject
* @throws MessagingException
*/
public void setSubject(String subject) throws MessagingException{
mimeMessage.setSubject(subject);
}
/**
* 設置日期
* @param date
* @throws MessagingException
*/
public void setDate(Date date) throws MessagingException{
mimeMessage.setSentDate(new Date());
}
/**
* 設置郵件文本內容
* @param text
* @throws MessagingException
*/
public void setText(String text) throws MessagingException{
mimeMessage.setText(text);
}
/**
* 設置郵件頭部
* @param arg0
* @param arg1
* @throws MessagingException
*/
public void setHeader(String arg0,String arg1) throws MessagingException{
mimeMessage.setHeader(arg0, arg1);
}
/**
* 設置郵件接收人地址 <單人發送>
* @param recipient
* @throws MessagingException
*/
public void setRecipient(String recipient) throws MessagingException{
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
/**
* 設置郵件接收人地址 <多人發送>
* @param list
* @throws MessagingException
* @throws AddressException
*/
public String setRecipients(List<String> recs) throws AddressException, MessagingException{
if(recs.isEmpty()){
return "接收人地址爲空!";
}
for(String str:recs){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
return "加入接收人地址成功!";
}
/**
* 設置郵件接收人地址 <多人發送>
* @param StringBuffer<parms,parms2,parms.....>
* @throws MessagingException
* @throws AddressException
*/
@SuppressWarnings("static-access")
public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{
if(sb==null||"".equals(sb)){
return "字符串數據爲空!";
}
Address []address = new InternetAddress().parse(sb.toString());
mimeMessage.addRecipients(Message.RecipientType.TO, address);
return "收件人加入成功";
}
/**
* 設置郵件發送人的名字
* @param from
* @throws UnsupportedEncodingException
* @throws MessagingException
*/
public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{
mimeMessage.setFrom(new InternetAddress(username,from));
}
/**
* 發送郵件<單人發送>
* return 是否發送成功
* @throws MessagingException
*/
public String sendMessage() throws MessagingException{
Transport.send(mimeMessage);
return "success";
}
/**
* 設置附件
* @param file 發送文件的路徑
*/
public void setMultipart(String file) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
multipart.addBodyPart(writeFiles(file));
mimeMessage.setContent(multipart);
}
/**
* 設置附件<添加多附件>
* @param fileList<接收List集合>
* @throws MessagingException
* @throws IOException
*/
public void setMultiparts(List<String> fileList) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
for(String s:fileList){
multipart.addBodyPart(writeFiles(s));
}
mimeMessage.setContent(multipart);
}
/**
* 發送文本內容,設置編碼方式
* <方法與發送附件配套使用>
* <發送普通的文本內容請使用setText()方法>
* @param s
* @param type
* @throws MessagingException
*/
public void setContent(String s,String type) throws MessagingException{
if(multipart==null){
multipart = new MimeMultipart();
}
bodypart = new MimeBodyPart();
bodypart.setContent(s, type);
multipart.addBodyPart(bodypart);
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
}
/**
* 讀取附件
* @param filePath
* @return
* @throws IOException
* @throws MessagingException
*/
public BodyPart writeFiles(String filePath)throws IOException, MessagingException{
File file = new File(filePath);
if(!file.exists()){
throw new IOException("文件不存在!請確定文件路徑是否正確");
}
bodypart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(dataSource));
//文件名要加入編碼,不然出現亂碼
bodypart.setFileName(MimeUtility.encodeText(file.getName()));
return bodypart;
}
}
三、測試
public
class TestSend
{
public TestSend(List<String> list,Map<String,String> message) throws MessagingException, IOException
{
Map<String,String> map= new HashMap<String,String>();
SendEmail mail = new SendEmail("[email protected]","pnvxllwznrnubbaf");
map.put("mail.smtp.host", "smtp.qq.com");
{
public TestSend(List<String> list,Map<String,String> message) throws MessagingException, IOException
{
Map<String,String> map= new HashMap<String,String>();
SendEmail mail = new SendEmail("[email protected]","pnvxllwznrnubbaf");
map.put("mail.smtp.host", "smtp.qq.com");
/*
* 添加收件人有三種方法:
* 1,單人添加(單人發送)調用setRecipient(str);發送String類型
* 2,多人添加(羣發)調用setRecipients(list);發送list集合類型
* 3,多人添加(羣發)調用setRecipients(sb);發送StringBuffer類型
*/
//list.add("***[email protected]");
mail.setRecipients(list);
mail.setSubject(message.get("title"));
mail.setDate(new Date());
mail.setFrom("***有限公司");
mail.setContent(message.get("content"), "text/html; charset=UTF-8");
System.out.println(mail.sendMessage());
}
}
成功