package com.zz.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class HuadaConfiguration {
private static ResourceBundle rb = null;
private static final String filePath = "mail.properties";
private static long lastModified = 0;
private static HuadaConfiguration config = new HuadaConfiguration();
private HuadaConfiguration() {
}
public static HuadaConfiguration getInstance() {
return config;
}
public String getValue(String key) {
if (rb == null) {
loadExceptionProperties();
}
if (checkFileUpdate()) {
loadExceptionProperties();
}
String result = rb.getString(key);
if (result == null) {
System.out.println("Can not find value in mail.properties");
throw new RuntimeException();
}
return result;
}
private boolean checkFileUpdate() {
URL fileUrl = getClass().getClassLoader().getResource(filePath);
File file = new File(fileUrl.getFile());
long time = file.lastModified();
if (time != lastModified) {
lastModified = time;
return true;
}
return false;
}
private void loadExceptionProperties() {
InputStream in = null;
try {
in = getClass().getClassLoader().getResourceAsStream(filePath);
rb = new PropertyResourceBundle(in);
} catch (FileNotFoundException e) {
System.out.println("Can Not file mail.properties!");
throw new RuntimeException(e);
} catch (IOException e) {
System.out.println("IOExecption when reading and parsing file mail.properties!");
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("Can not close Stream mail.properties!");
throw new RuntimeException(e);
}
}
}
}
}
2Po類
package com.zz.util;
/**
* 發送郵件需要使用的基本信息
*/
import java.util.Properties;
public class MailSenderInfo {
// 發送郵件的服務器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 郵件發送者的地址
private String fromAddress;
// 郵件接收者的地址
private String toAddress;
// 登陸郵件發送服務器的用戶名和密碼
private String userName;
private String password;
// 是否需要身份驗證
private boolean validate = true;
// 郵件主題
private String subject;
// 郵件的文本內容
private String content;
// 郵件附件的文件名
private String[] attachFileNames;
/**
* 獲得郵件會話屬性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
設置密碼和郵箱用戶名的Pojo類
package com.zz.util;
import javax.mail.*;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
這個類是發郵件的核心類
package com.zz.util;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
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 SimpleMailSender {
/**
* 以文本格式發送郵件
* @param mailInfo 待發送的郵件的信息
*/
public static boolean sendTextMail(MailSenderInfo mailInfo) {
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份認證,則創建一個密碼驗證器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據session創建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創建郵件發送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發送者
mailMessage.setFrom(from);
// 創建郵件的接收者地址,並設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發送的時間
mailMessage.setSentDate(new Date());
//放入內容和附件類
MimeMultipart allMultipart = new MimeMultipart("mixed");
//設置內容
MimeBodyPart HtmlBodypart = new MimeBodyPart();
// 設置郵件消息的主要內容
String mailContent = mailInfo.getContent();
HtmlBodypart.setContent(mailContent,"text/html;charset=gbk");
//設置附件
MimeBodyPart attachFileBodypart = new MimeBodyPart();
MimeMultipart attachFileMMP = new MimeMultipart("related");
String[] strArrgs = mailInfo.getAttachFileNames(); //所有文件路徑
for(int i = 0; i < strArrgs.length; i++) {
MimeBodyPart attachFileBody = new MimeBodyPart();
FileDataSource fds = new FileDataSource(new File(strArrgs[i]));//附件文件
attachFileBody.setDataHandler(new DataHandler(fds));//得到附件本身並至入BodyPart
//MimeUtility.encodeText()解決文件名亂碼問題
attachFileBody.setFileName(MimeUtility.encodeText(fds.getName()));//得到文件名同樣至入BodyPart
attachFileMMP.addBodyPart(attachFileBody);//放入BodyPart
}
attachFileBodypart.setContent(attachFileMMP,"text/html;charset=gbk");
//放入內容
allMultipart.addBodyPart(HtmlBodypart);
//放入附件
allMultipart.addBodyPart(attachFileBodypart);
mailMessage.setContent(allMultipart);
mailMessage.saveChanges();
//文件內容寫在本地,測試 用
mailMessage.writeTo(new FileOutputStream("D:/ComplexMessage.eml"));
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
/**
* 以HTML格式發送郵件
* @param mailInfo 待發送的郵件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份認證,則創建一個密碼驗證器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據session創建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創建郵件發送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發送者
mailMessage.setFrom(from);
// 創建郵件的接收者地址,並設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型爲TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創建一個包含HTML內容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 設置HTML內容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 將MiniMultipart對象設置爲郵件內容
mailMessage.setContent(mainPart);
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
測試類
package com.zz.mail;
import com.zz.util.HuadaConfiguration;
import com.zz.util.MailSenderInfo;
import com.zz.util.SimpleMailSender;
public class SendMail {
public static void main(String[] args) {
//這個類主要是設置郵件
MailSenderInfo mailInfo = new MailSenderInfo();
HuadaConfiguration huadaConfiguration = HuadaConfiguration.getInstance();
mailInfo.setMailServerHost(huadaConfiguration.getValue("mailServerHost"));
mailInfo.setMailServerPort(huadaConfiguration.getValue("mailServerPort"));
mailInfo.setValidate(true);
mailInfo.setUserName(huadaConfiguration.getValue("userName"));
mailInfo.setPassword(huadaConfiguration.getValue("password"));//您的郵箱密碼
mailInfo.setFromAddress(huadaConfiguration.getValue("fromAddress"));
mailInfo.setToAddress("[email protected]");
mailInfo.setSubject("測試郵箱標題附件");
mailInfo.setContent("測試郵箱內容");
mailInfo.setAttachFileNames(new String[]{"D:/1.docx","D:/2.docx","D:/資料/照片/單反/1/DSC_0031.JPG"});
SimpleMailSender.sendTextMail(mailInfo);
}
}
一些文檔路徑問題,請修改下