package com.xxx.task;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
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;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.ContextLoader;
import com.hotent.core.util.AppConfigUtil;
import com.hotent.core.web.util.RequestContext;
import com.xxx.util.BpmFormUtilService;
import com.xxx.util.POIExcelToHtml;
/**
* 功能:定时自动导出报告,数据打包发邮件。初定每天凌晨两点。定时配置文件job.properties, 查找 w_export_template 表中数据,
*/
public class MailTask2 {
@Resource
private BpmFormUtilService bpmFormUtilService;
@Resource
private JdbcTemplate jdbcTemplate;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private String contentPart_Type = "";
private MimeMessage message;
private Properties properties = new Properties();
/*
* 初始化方法
*/
public void JavaMailWithAttachment() {
try {
// 获取邮箱配置信息
ResourceBundle resource = ResourceBundle.getBundle("conf/app");
//mail.port3=25
//mail.from3=abc@xxx.com
//mail.host3=smtp.xxx.com
//mail.password3=xxx.aaa
this.mailHost = resource.getString("mail.host3");
this.sender_username = resource.getString("mail.from3");
this.sender_password = resource.getString("mail.password3");
this.contentPart_Type = "text/html;charset=UTF-8";
} catch (Exception e) {
e.printStackTrace();
}
session = Session.getInstance(properties);
session.setDebug(true); //开启后有调试信息,发布时关闭
message = new MimeMessage(session);
}
/**
* 发送邮件
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param toUser
* 收件人 多个时参数形式 : "xxx@xxx.com,xxx@xxx.com,xxx@xxx.com"
* @param ccUser
* 抄送人 同上
* @param bccUser
* 密送人 同上
* @param attachment
* 附件
* @param imgFile
* 图片附件
*/
public void doSendHtmlEmail(String subject, String sendHtml,
String toUser, String ccUser, String bccUser, File [] attachment, File imgFile){
try {
JavaMailWithAttachment();
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
// 设置多个收件人地址
if(null != toUser && !toUser.isEmpty()){
@SuppressWarnings("static-access")
String [] mailTos = {};
InternetAddress[] internetAddressTo = new InternetAddress().parse(toUser);
message.setRecipients(Message.RecipientType.TO, internetAddressTo);
}
// 设置多个抄送地址
if(null != ccUser && !ccUser.isEmpty()){
@SuppressWarnings("static-access")
InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
message.setRecipients(Message.RecipientType.CC, internetAddressCC);
}
// 设置多个密送地址
if(null != bccUser && !bccUser.isEmpty()){
@SuppressWarnings("static-access")
InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
}
// 发送日期
message.setSentDate(new Date());
// 邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
MimeBodyPart imagePart = new MimeBodyPart();//图片对象
//处理正文内容不换行
if(sendHtml!=null && !"".equals(sendHtml.trim()))
sendHtml = sendHtml.replaceAll("\n", "<br>").replaceAll("\n", "<BR>");
else
sendHtml = "";
// 添加图片正文标识
if(imgFile.exists()){
sendHtml += "<BR><img src='cid:mailContentPng'/>";
}
contentPart.setContent(sendHtml, contentPart_Type);
multipart.addBodyPart(contentPart);
BodyPart attachmentBodyPart = null;
// 添加图片正文
if(imgFile.exists()){
DataSource ds = new FileDataSource(imgFile);
DataHandler dh = new DataHandler(ds);
imagePart.setDataHandler(dh);
imagePart.setContentID("mailContentPng");//对应正文的标记位置
multipart.addBodyPart(imagePart);
}
// 添加附件的内容
if (null != attachment && attachment.length != 0) {
for (File file : attachment) {
attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
// smtp验证
transport = session.getTransport("smtp");
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
/**
* 返回文件大小的mb
* @param file
* @return
*/
public Double getFileSizeMB(File file)throws Exception{
Double size = 0.0;
if(file.exists() && file.isFile()){
long fileS = file.length();
DecimalFormat df = new DecimalFormat("#.00");
size = Double.valueOf(df.format((double) fileS / 1048576)); //+ "MB";
}else if(file.exists() && file.isDirectory()){
size = 0.0;
}else{
size = 0.0;//+ "MB";
}
return size;
}
/**
* 邮件地址验证,排查重复地址,返回正确地址
* @param address
* @return
*/
public String checkEmailAddress(String address){
String [] add = address.split(",");
// 去重用
Set set = new HashSet();
String eMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; // email格式验证
for(int k=0; k<add.length; k++){
Boolean b = add[k].matches(eMAIL_REGEX);
if(!b){
// this.insertMailStatus(subject, context, mTo, "定时发送"
//, "邮件地址异常","",0.0, sendType, form_key, form_name, exportTemplateId);
continue;
}
set.add( add[k] );
}
return set.size()>0? ( set.toString().replaceAll(" ", "").replace("[","").replace("]", "") ):"";
}
public static void main(String args[]) throws Exception{
MailTask2 m = new MailTask2();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
File f = new File("/D:/tools/Tools4.zip");
System.out.println(m.getFileSizeMB(f));
try {
//m.insertMailStatus("subject", "context", "mailTo", "exception");
//System.out.println(new Date());
//m.exportData();
//m.taskCycle();
}catch(Exception e){
e.printStackTrace();
}
try {
String eMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";//email格式验证
String files = "/D:/dashboard/TMP_EXPORT"; // 整个文件夹中的文件
String imgFiles = "/D:/ludashi.jpg";
File [] attachment = new File(files).listFiles();
File imgFile = new File(imgFiles);
String address = "abc@163.com,abc@163.xxcom,abc@21cn.com,abc@qq.com";
address = m.checkEmailAddress(address);
String [] add = address.split(";");
InternetAddress[] sendTo = new InternetAddress[add.length];
String ccUser = "abc@163.com";
m.doSendHtmlEmail("邮件服务查收", "亲爱的用户您好!<br>欢迎你加入!!!!", address, ccUser, null, null, imgFile );
} catch (Exception e) {
e.printStackTrace();
}
}
}
javamail多收件人、多抄送、多附件、邮件正文加图片
最新推荐文章于 2024-03-22 18:08:26 发布