随着业务的复杂度,一般意义上的电子邮件无法满足需求,有些邮件需要附带 url附件文件。
具体公共类 MailUtils.java
如下
package com;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
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.mail.util.ByteArrayDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MailUtils {
private String host;
private String port;
private String user;
private String password;
private String userName;
private String userNm_charset;
static Logger logger = LoggerFactory.getLogger(MailUtils.class);
/**
* 发件,信息初始化
* @param host 邮件SMTP服务器
* @param port SMTP服务器端口号
* @param user 发件人邮箱
* @param password 发件人邮箱密码
* @param userName 发件人名字
*/
public MailUtils(String host,String port, String user, String password,String userName,String userNm_charset){
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.userName = userName;
this.userNm_charset = userNm_charset;
}
/**
* 开始发件
*
* 说明 1,本地文件(fileName、in、inType 必须同时有值),
* 2,网路文件(fileName、fpPdf 必须同时有值)
*
* @param title 邮件标题
* @param toMail 收件人邮箱
* @param content 邮件正文
* @param fileName 附件名
* @param in 附件文件流
* @param inType 附件文件类型
* @param fpPdf 附件url
* @param ccList 抄送人邮箱
* @return
*/
public boolean sendMail(String title, String toMail, String content,String fileName, InputStream in,String inType,String fpPdf,String ccList) {
boolean isFlag = false;
try {
Properties props = new Properties();
props.put("mail.smtp.host", host); // 指定SMTP服务器
props.put("mail.smtp.port", port); // 指定SMTP服务器端口号
props.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);// 设置信任所有的主机
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
//props.put("mail.smtp.timeout", "25000");//超时时间
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
MimeMessage message = new MimeMessage(session);
try {
//指定发送人
if(userName!=null && !"".equals(userName)){
if(userNm_charset==null || "".equals(userNm_charset)){
userNm_charset = "utf-8";
}
message.setFrom(new InternetAddress(user,userName,userNm_charset));
}else{
message.setFrom(new InternetAddress(user));
}
//指定接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
//指定抄送人
if(ccList!=null || !"".equals(ccList)){
message.addRecipients(Message.RecipientType.CC,ccList);
}
//设置标题
message.setSubject(title,"UTF-8");
message.addHeader("charset", "UTF-8");
/*添加正文内容*/
//一个Multipart对象包含一个或多个bodypart对象,组成邮件正文
Multipart multipart = new MimeMultipart();
MimeBodyPart contentPart = new MimeBodyPart();
contentPart.setText(content,"UTF-8");
contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
multipart.addBodyPart(contentPart);
/*添加附件*/
if(in != null) {
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(in, inType);//"application/msexcel"
fileBody.setDataHandler(new DataHandler(source));
// 中文乱码问题
fileBody.setFileName(MimeUtility.encodeText(fileName));
multipart.addBodyPart(fileBody);
}
if(in == null && fpPdf != null) {
MimeBodyPart fileBody = new MimeBodyPart();
URL url = new URL(fpPdf);
DataSource dataSource=new URLDataSource(url);
DataHandler dataHandler=new DataHandler(dataSource);
fileBody.setDataHandler(dataHandler);
// 中文乱码问题
fileBody.setFileName(MimeUtility.encodeText(fileName));
multipart.addBodyPart(fileBody);
}
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isFlag = true;
logger.info(Calendar.getInstance().getTime()+":#Send mail to"+toMail+"success #");
} catch (Exception e) {
logger.info(Calendar.getInstance().getTime()+":#Send mail to"+toMail+"error #");
logger.info(e.toString());
e.printStackTrace();
isFlag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return isFlag;
}
}
引用公共类
如下:
logger.info("发送邮件------>>>userEmail:{},charset:{}",userEmail,mail_userNm_charset);
MailUtils mailUtils = new MailUtils(mail_host,mail_port,mail_user,mail_pass,mail_userNm,mail_userNm_charset);
String title = "订单"+orderNo+"发票";
//收件人
String toMail = userEmail;
//正文
String content = "<h1 align=\"center\">迪信通电子发票</h1>"
+"<p>你好:</p>"
+"<p style=\"padding-left:2em;\">你申请的电子发票,详见<font style=\"font-weight:bold;color:#0000cc;font-size:20px\">附件</font>。</p>"
+"<p style=\"padding-left:2em;\">如未能打开,请<a target=\"_blank\" href=\""+eleInvoice.getFpUrl()+"\">点击链接</a>查看:"+eleInvoice.getFpUrl()+"</p>";
//附件文件名
String fileName = "订单"+orderNo+"电子发票.pdf";
//附件文件流
InputStream in = null;
//附件文件类型
String inType = "";
//抄送
String ccList = "";
mailUtils.sendMail(title, toMail, content, fileName, in,inType,eleInvoice.getFpUrl(), ccList);