參考網站:http://www.open-open.com/code/view/1420037773921html
http://blog.sina.com.cn/s/blog_59ca2c2a01013800.htmljava
一,參數類web
package com.camelot.util.mail;spring
import java.util.Properties;
import java.util.Vector;服務器
import javax.mail.internet.MimeUtility;session
/**
* <p>Description: [郵件util]</p>
* Created on 2017年1月5日
* @author <a href="mailto: wnaghaibo@camelotchina.com">王海波</a>
* @version 2.0
* Copyright (c) 2017 北京柯萊特科技有限公司
*/
public class MailSenderInfo {
// 發送郵件的服務器的IP(或主機地址)
private String mailServerHost;
// 發送郵件的服務器的端口
private String mailServerPort;
// 發件人郵箱地址
private String fromAddress;
// 收件人郵箱地址
private String toAddress;
// 登錄郵件發送服務器的用戶名
private String userName;
// 登錄郵件發送服務器的密碼
private String password;
// 是否須要身份驗證
private boolean validate = false;
// 郵件主題
private String subject;
// 郵件的文本內容
private String content;
// 郵件附件的文件名
private String[] attachFileNames;
Vector file = new Vector();// 附件文件集合
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 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;
}
/**
* <br>
* 方法說明:把主題轉換爲中文 <br>
* 輸入參數:String strText <br>
* 返回類型:
*/
public String transferChinese(String strText) {
try {
strText = MimeUtility.encodeText(new String(strText.getBytes(),
"GB2312"), "GB2312", "B");
} catch (Exception e) {
e.printStackTrace();
}
return strText;
}
public void attachfile(String attachFileNames) {
file.addElement(attachFileNames);
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames;
}
}oracle
二,發送郵件類app
package com.camelot.util.mail;測試
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.annotation.Resource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.camelot.ituber.sdk.export.dto.ResStandardResumeDTO;
import com.camelot.ituber.sdk.export.service.ResStandardResumeExportService;
import com.camelot.openplatform.common.bean.ExecuteResult;
import com.camelot.util.resume.PropertiesUtil;
/**
* <p>Description: [發送郵件]</p>
* Created on 2017年1月5日
*/
@Controller
@RequestMapping(value="/SimpleMailSender")
public class SimpleMailSender {
@Resource
private ResStandardResumeExportService resStandardExportService;
/**
* 發送郵件
* 需傳入附件id集合
* 標準簡歷數據
* mailInfo郵件類初始化數據
* @param mailInfo
* @param resStandardResume
* @return
*/
@RequestMapping(value="/sendMail")
public ExcameStatus sendMail(HttpServletRequest request,MailSenderInfo mailInfo,ResStandardResumeDTO resStandardResume) {
List<Integer> l = new ArrayList<Integer>();
l.add(11);
resStandardResume.setIds(l);
ExcameStatus es = new ExcameStatus();
List<Integer> list = resStandardResume.getIds();
List<ResStandardResumeDTO> resumeList = new ArrayList<ResStandardResumeDTO>();
//獲取標準簡歷附件數據放入list
for (int i = 0; i < list.size(); i++) {
ExecuteResult<ResStandardResumeDTO> primaryKey = new ExecuteResult<ResStandardResumeDTO>();
if(list.get(i)!=null&&list.get(i)>0){
primaryKey = resStandardExportService.selectByResId(list.get(i));
if(primaryKey.getResult()!=null){
resumeList.add(primaryKey.getResult());
}
}
}
// 設置郵件服務器信息
MailSenderInfo mailInfos = new MailSenderInfo();
mailInfos.setMailServerHost(PropertiesUtil.getValue("mailServerHost"));////smtp-mail.outlook.com
mailInfos.setMailServerPort(PropertiesUtil.getValue("mailServerPort"));//587
mailInfos.setValidate(true);
// 郵箱用戶名
mailInfos.setUserName("15801662503@163.com");
// 郵箱密碼
mailInfos.setPassword("wanghaibo123");
// 發件人郵箱
mailInfos.setFromAddress("15801662503@163.com");//wanghaibo2503@outlook.com
// 收件人郵箱
mailInfos.setToAddress("329765964@qq.com");
// 郵件標題
mailInfos.setSubject("aaa");
// 郵件內容
mailInfos.setContent("bbb");
//處理附件
String[] fileNames = new String[resumeList.size()];
String htmlFileName = null;
for (int i = 0; i < resumeList.size(); i++) {
try {
htmlFileName = Html2word.Word2003ToHtml(request);
es = new Html2word().writeWordFile(request,htmlFileName,resumeList.get(i));
if(es.getPath()!=null){
fileNames[i] = es.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
}
mailInfos.setAttachFileNames(fileNames);
// 發送郵件
boolean b = SimpleMailSender.sendHtmlMail(mailInfos);
//刪除文件
if(b){
for (int i = 0; i < resumeList.size(); i++) {
File tempFile =new File(fileNames[i].trim());
// 路徑爲文件且不爲空則進行刪除doc
if (tempFile.isFile() && tempFile.exists()) {
tempFile.delete();
}
}
File tempFile1 =new File(htmlFileName.trim());
// 路徑爲文件且不爲空則進行刪除html
if (tempFile1.isFile() && tempFile1.exists()) {
tempFile1.delete();
}
}
return es;
}
/**
*
* @param mailInfo
* @return
*/
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=GBK");
mainPart.addBodyPart(html);
// 爲郵件添加附件
String[] attachFileNames = mailInfo.getAttachFileNames();
if (attachFileNames != null && attachFileNames.length > 0) {
// 存放郵件附件的MimeBodyPart
MimeBodyPart attachment = null;
File file = null;
for (int i = 0; i < attachFileNames.length; i++) {
attachment = new MimeBodyPart();
// 根據附件文件建立文件數據源
file = new File(attachFileNames[i]);
FileDataSource fds = new FileDataSource(file);
attachment.setDataHandler(new DataHandler(fds));
// 爲附件設置文件名
attachment.setFileName(MimeUtility.encodeWord(
file.getName(), "GBK", null));
mainPart.addBodyPart(attachment);
}
}
// 將MiniMultipart對象設置爲郵件內容
mailMessage.setContent(mainPart);
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// 設置郵件服務器信息
MailSenderInfo mailInfo1 = new MailSenderInfo();
mailInfo1.setMailServerHost("smtp.163.com");////smtp-mail.outlook.com
mailInfo1.setMailServerPort("25");//587
mailInfo1.setValidate(true);
// 郵箱用戶名
mailInfo1.setUserName("15801662503@163.com");
// 郵箱密碼
mailInfo1.setPassword("wanghaibo123");
// 發件人郵箱
mailInfo1.setFromAddress("15801662503@163.com");//wanghaibo2503@outlook.com
// 收件人郵箱
mailInfo1.setToAddress("329765964@qq.com");
// 郵件標題
mailInfo1.setSubject("測試Java程序發送郵件");
// 郵件內容
StringBuffer buffer = new StringBuffer();
buffer.append("JavaMail 1.4.5 jar包下載地址:http://www.oracle.com/technetwork/java/index-138643.html\n");
buffer.append("JAF 1.1.1 jar包下載地址:http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html");
mailInfo1.setContent(buffer.toString());
List<ResStandardResumeDTO> resumeList = new ArrayList<ResStandardResumeDTO>();
ResStandardResumeDTO resume = new ResStandardResumeDTO();
resume.setBasicInformation("姓名:王波波");
resume.setSelfAssessment("<div>我愛中國!!!<div>");
resume.setProjectExperience("<div style=\"color:'red'\">ITUBER</div>");
resume.setWorkExperience("<div>北京科技公司<div>");
resumeList.add(resume);
ResStandardResumeDTO resume1 = new ResStandardResumeDTO();
resume1.setBasicInformation("姓名:王波波1");
resume1.setSelfAssessment("<div>我愛中國1!!!<div>");
resume1.setProjectExperience("<div style=\"color:'red'\">ITUBER</div>");
resume1.setWorkExperience("<div>北京科技公司<div>");
resumeList.add(resume1);
String[] fileNames = new String[resumeList.size()];
/* for (int i = 0; i < resumeList.size(); i++) {
try {
String htmlFileName = Html2word.Word2003ToHtml();
ExcameStatus excame = new Html2word().writeWordFile(htmlFileName,resumeList.get(i));
if(excame.getPath()!=null){
fileNames[i] = excame.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
}
mailInfo1.setAttachFileNames(fileNames);*/
// 發送郵件
// SimpleMailSender sms = new SimpleMailSender();
// 發送文體格式
// sms.sendTextMail(mailInfo);
// 發送html格式
SimpleMailSender.sendHtmlMail(mailInfo1);
System.out.println("郵件發送完畢");
}
}
三,返回類
package com.camelot.util.mail;
public class ExcameStatus {
private Boolean flag;
private String path ;
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public String getPath() {
return path;
}
public void setPath(String path) { this.path = path; } }