Java封裝好的mail包發(fā)送電子郵件的類
下面代碼是利用Java mail包封裝了一個(gè)發(fā)送郵件的類
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
public class SendMail {
private static final String MAIL_ADDRESS_REGEX = "^[\\w\\.=-]+@[\\w\\.-]+\\.[\\w]{2,3}$";
private String mailServer;
private String sender;
private String[] receiver;
public SendMail(){
}
public void setMailBasicInfo(String mailServer,String sender,String receiver){
this.mailServer = mailServer;
this.sender = sender;
this.receiver =receiver.split(",");
}
public void setMailBasicInfo(String mailServer,String sender,String[] users){
this.mailServer = mailServer;
this.sender = sender;
this.receiver = users;
}
public void setMailBasicInfo(String mailServer,String sender,List<String> users){
this.mailServer = mailServer;
this.sender = sender;
this.receiver = new String[users.size()];
users.toArray(this.receiver);
}
public boolean send(String subject, String content, List<String> fileNames)
{
subject = subject==null?"":subject;
content = content==null?"":content;
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
Session session = Session.getInstance(props, null);
try
{
InternetAddress[] receiver = getReceiverList();
if (receiver.length == 0)
{
System.out.println("receiver is null");
return false;
}
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.setRecipients(Message.RecipientType.TO, receiver);
msg.setSubject(subject);
msg.setSentDate(new Date());
Multipart container = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content.toString(), "text/html;charset=gbk");
container.addBodyPart(textBodyPart);
doAttachFile(container,fileNames);
msg.setContent(container);
System.out.println("begin send mail");
Transport.send(msg);
System.out.println("send mail success");
}
catch (MessagingException e)
{
System.out.println("send mail fail");
System.out.println(e);
return false;
}
catch(Exception e){
return false;
}
return true;
}
public boolean send(String subject, String content){
return send(subject,content,null);
}
public boolean send(String subject){
return send(subject,null);
}
private void doAttachFile(Multipart container, List<String> fileNames) throws MessagingException{
if(fileNames==null || fileNames.size()==0)
return;
for(String filename:fileNames){
File f = new File(filename);
if(!f.isFile())
continue;
System.out.println("the attach file is:"+filename);
MimeBodyPart fileBodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(f);// 要發(fā)送的附件地址
fileBodyPart.setDataHandler(new DataHandler(fds));
fileBodyPart.setFileName(fds.getName());// 設(shè)置附件的名稱
container.addBodyPart(fileBodyPart);
}
}
private InternetAddress[] getReceiverList() throws AddressException
{
ArrayList<InternetAddress> toList = new ArrayList<InternetAddress>();
for (int i = 0; i < receiver.length; ++i)
{
if (receiver[i].matches(MAIL_ADDRESS_REGEX))
{
toList.add(new InternetAddress(receiver[i]));
}
}
return (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]);
}
}
使用舉例
String host = "168.xx.xx.xx"; //郵件服務(wù)器的地址
String subject = "發(fā)送郵件的主題";
String sender = "test@gmail.com";
List<String> receivers = new ArrayList<String>();
receivers.add("user1@263.com");
receivers.add("user2@263.com");
String content = "郵件主題";
SendMail sendMail = new SendMail();
sendMail.setMailBasicInfo(host, sender, receivers);
sendMail.send(subject, content, null); //沒(méi)有附件
正文也可以是html內(nèi)容,如
String content = "<html>詳細(xì)信息:<a href='xxxx'>請(qǐng)點(diǎn)擊查看!</a></html>";
我們?cè)賮?lái)看一個(gè)封裝好的類
package com.message.base.email;
import com.message.base.spring.ApplicationHelper;
import com.message.base.utils.StringUtils;
import com.message.base.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
* 發(fā)送郵件服務(wù)器.
*
* @author sunhao(sunhao.java@gmail.com)
* @version V1.0, 13-3-25 上午6:19
*/
public class EmailServer {
private static final Logger logger = LoggerFactory.getLogger(EmailServer.class);
//spring中配置
/**郵箱服務(wù)器配置**/
private List<EmailConfig> config;
/**是否開(kāi)啟debug調(diào)試模式**/
private boolean isDebug = false;
/**是否啟用身份驗(yàn)證**/
private boolean isAuth = true;
/**驗(yàn)證類型**/
private String authType = "auth";
/**
* 私有化默認(rèn)構(gòu)造器,使外部不可實(shí)例化
*/
private EmailServer(){}
/**
* 單例,保證上下文中只有一個(gè)EmailServer
*
* @return EmailServer
*/
public static EmailServer getInstance(){
return ApplicationHelper.getInstance().getBean(EmailServer.class);
}
/**
* 發(fā)送普通郵件(單個(gè)接收人)
*
* @param username 發(fā)件人用戶名
* @param password 發(fā)件人密碼
* @param title 郵件標(biāo)題
* @param content 郵件正文
* @param receiver 單個(gè)接收人
* @return
*/
public boolean sendTextMail(String username, String password, String title, String content, String receiver){
return this.sendTextMail(username, password, title, content, Collections.singletonList(receiver));
}
/**
* 發(fā)送普通郵件(多個(gè)接收人)
*
* @param username 發(fā)件人用戶名
* @param password 發(fā)件人密碼
* @param title 郵件標(biāo)題
* @param content 郵件正文
* @param receivers 多個(gè)接收人
* @return
*/
public boolean sendTextMail(String username, String password, String title, String content, List<String> receivers){
Authentication auth = null;
if(this.isAuth()){
//如果需要身份認(rèn)證,則創(chuàng)建一個(gè)密碼驗(yàn)證器
auth = new Authentication(username, password);
}
Properties props = new Properties();
props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
props.setProperty("mail.transport.protocol", "auth");
EmailConfig config = this.getEmailConfig(username);
props.setProperty("mail.smtp.host", config.getSmtp());
props.setProperty("mail.smtp.port", config.getPort() + "");
// 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(this.isDebug);
Message message = this.makeTextMail(session, title, content, username, receivers, false);
try {
Transport.send(message);
return true;
} catch (MessagingException e) {
logger.error(e.getMessage(), e);
return false;
}
}
/**
* 發(fā)送HTML郵件(單個(gè)接收人)
*
* @param username 發(fā)件人用戶名
* @param password 發(fā)件人密碼
* @param title 郵件標(biāo)題
* @param content 郵件正文
* @param receiver 單個(gè)接收人
* @return
*/
public boolean sendHtmlMail(String username, String password, String title, String content, String receiver){
return this.sendHtmlMail(username, password, title, content, Collections.singletonList(receiver));
}
/**
* 發(fā)送HTML郵件(多個(gè)接收人)
*
* @param username 發(fā)件人用戶名
* @param password 發(fā)件人密碼
* @param title 郵件標(biāo)題
* @param content 郵件正文
* @param receivers 多個(gè)接收人
* @return
*/
public boolean sendHtmlMail(String username, String password, String title, String content, List<String> receivers){
Authentication auth = null;
if(this.isAuth()){
//如果需要身份認(rèn)證,則創(chuàng)建一個(gè)密碼驗(yàn)證器
auth = new Authentication(username, password);
}
Properties props = new Properties();
props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
props.setProperty("mail.transport.protocol", "auth");
EmailConfig config = this.getEmailConfig(username);
props.setProperty("mail.smtp.host", config.getSmtp());
props.setProperty("mail.smtp.port", config.getPort() + "");
// 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(this.isDebug);
Message message = this.makeTextMail(session, title, content, username, receivers, true);
try {
Transport.send(message);
return true;
} catch (MessagingException e) {
logger.error(e.getMessage(), e);
return false;
}
}
/**
* 獲取郵件服務(wù)器配置
*
* @param email 郵箱地址
* @return
*/
private EmailConfig getEmailConfig(String email){
String mailServiceDomainName = this.getMailServiceDomainName(email);
for(EmailConfig config : this.config) {
if(config.getName().equals(mailServiceDomainName)){
return config;
}
}
return null;
}
/**
* 創(chuàng)建郵件message
*
* @param session 根據(jù)配置獲得的session
* @param title 郵件主題
* @param content 郵件的內(nèi)容
* @param from 發(fā)件者
* @param receivers 收件者
* @param isHtmlMail 是否是html郵件
*/
private Message makeTextMail(Session session, String title, String content, String from, List<String> receivers, boolean isHtmlMail){
Message message = new MimeMessage(session);
try {
/**標(biāo)題**/
logger.info("this mail's title is {}", title);
message.setSubject(title);
/**內(nèi)容**/
logger.info("this mail's content is {}", content);
if(isHtmlMail){
//是html郵件
message.setContent(content, "text/html;charset=utf-8");
} else {
//普通郵件
message.setText(content);
}
/**發(fā)件者地址**/
logger.info("this mail's sender is {}", from);
Address fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
/**接收者地址**/
Address[] tos = new InternetAddress[receivers.size()];
for(int i = 0; i < receivers.size(); i++){
String receiver = receivers.get(i);
if(ValidateUtils.isEmail(receiver)){
tos[i] = new InternetAddress(receiver);
}
}
/**發(fā)件時(shí)間**/
message.setSentDate(new Date());
message.setRecipients(Message.RecipientType.TO, tos);
} catch (MessagingException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
}
return message;
}
/**
* 獲取郵箱域名
*
* @param email 郵箱
* @return
*/
private String getMailServiceDomainName(String email){
if(StringUtils.isEmpty(email)){
return "";
} else {
int firstIndex = StringUtils.indexOf(email, "@");
int secondIndex = StringUtils.lastIndexOf(email, ".");
return StringUtils.substring(email, firstIndex + 1, secondIndex);
}
}
public List<EmailConfig> getConfig() {
return config;
}
public void setConfig(List<EmailConfig> config) {
this.config = config;
}
public boolean isDebug() {
return isDebug;
}
public void setDebug(boolean debug) {
isDebug = debug;
}
public boolean isAuth() {
return isAuth;
}
public void setAuth(boolean auth) {
isAuth = auth;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
}
調(diào)用方式如下
public boolean sendMail() throws Exception {
List<String> receivers = new ArrayList<String>();
receivers.add("sunhao0550@163.com");
receivers.add("sunhao0550@sina.cn");
EmailServer.getInstance().sendHtmlMail("message_admin@163.com", "這里是密碼", "測(cè)試發(fā)送HTML郵件",
"<span style='color: red;font-size: 20pt'>測(cè)試發(fā)送HTML郵件</span><a target='_blank'>鏈接到百度</a>", receivers);
return EmailServer.getInstance().sendTextMail("message_admin@163.com", "這里是密碼", "測(cè)試發(fā)送文本郵件",
"測(cè)試發(fā)送文本郵件測(cè)試發(fā)送文本郵件測(cè)試發(fā)送文本郵件", receivers);
}
PS:正在考慮擴(kuò)展,如果把這幾個(gè)類封在jar包中,如何進(jìn)行郵件服務(wù)器配置的擴(kuò)展.
如有不好之處,歡迎拍磚.
- Javamail使用過(guò)程中常見(jiàn)問(wèn)題解決方案
- java結(jié)合email實(shí)現(xiàn)自動(dòng)推送功能
- 淺析JavaMail發(fā)送郵件后再通過(guò)JavaMail接收格式問(wèn)題
- java常用工具類 Date日期、Mail郵件工具類
- Spring框架JavaMailSender發(fā)送郵件工具類詳解
- java工具類SendEmailUtil實(shí)現(xiàn)發(fā)送郵件
- JavaMailSender實(shí)現(xiàn)郵箱驗(yàn)證功能
- JavaMail發(fā)送(帶圖片和附件)和接收郵件實(shí)現(xiàn)詳解(四)
- Java Mail郵件發(fā)送如何實(shí)現(xiàn)簡(jiǎn)單封裝
相關(guān)文章
Java中outer標(biāo)簽的用法實(shí)例代碼
這篇文章主要介紹了Java中outer標(biāo)簽的用法,在這里需要大家注意這里的outer并不是關(guān)鍵字,而僅僅是一個(gè)標(biāo)簽,本文結(jié)合實(shí)例代碼給大家詳細(xì)講解,需要的朋友可以參考下2023-01-01
Java高級(jí)特性之反射機(jī)制實(shí)例詳解
這篇文章主要介紹了Java高級(jí)特性之反射機(jī)制,結(jié)合實(shí)例形式詳細(xì)分析了Java反射機(jī)制原理、功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-08-08
Java讀取resources中資源文件路徑以及jar中文件無(wú)法讀取的解決
這篇文章主要介紹了Java讀取resources中資源文件路徑以及jar中文件無(wú)法讀取的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
Hibernate懶加載之<class>標(biāo)簽上的lazy
這篇文章主要介紹了Hibernate懶加載之<class>標(biāo)簽上的lazy,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
java基礎(chǔ)學(xué)習(xí)JVM中GC的算法
這篇文章主要介紹了java基礎(chǔ)學(xué)習(xí)JVM中GC的算法,通過(guò)圖文加深對(duì)GC算法思路的理解。2017-11-11
mybatis如何設(shè)置useGeneratedKeys=true
這篇文章主要介紹了mybatis如何設(shè)置useGeneratedKeys=true,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2022-01-01
java 中HttpClient傳輸xml字符串實(shí)例詳解
這篇文章主要介紹了java 中HttpClient傳輸xml字符串實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04

