java mail包括多个附件

it2022-05-05  69

参考网站:http://www.open-open.com/code/view/1420037773921

http://blog.sina.com.cn/s/blog_59ca2c2a01013800.html

 

一,参数类

package com.camelot.util.mail;

import java.util.Properties;import java.util.Vector;

import javax.mail.internet.MimeUtility;

/** * <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; }}

 

 

 

二,发送邮件类

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; } }

转载于:https://www.cnblogs.com/whb11/p/6273553.html

相关资源:JavaMail发送给多人,添加多个附件

最新回复(0)