public class SendMailUtil {
@Value("${email.host}")
private String HOST;// smtp服务器
@Value("${email.from}")
private String FROM;// 发件人地址
//@Value("${email.to}")
private String TO;// 收件人地址
@Value("${email.affix}")
private String AFFIX; // 附件地址
@Value("${email.affixzip}")
private String AFFIXZIP;// 打包后文件路径
@Value("${email.user}")
private String USER;// 用户名
@Value("${email.pwd}")
private String PWD;// 163的授权码
//@Value("${email.subject}")
private String SUBJECT; // 邮件标题
String[] TOS = null;
/*@Autowired
private FileUtil fileUtil;*/
private static Log logger = LogFactory.getLog(SendMailUtil.class);
/**
* 发送邮件
*
* @param context //邮件内容
* @param TOReceiver //收件人
* @param subject 邮件主题
* @param ifattachment 是否发送附件
* @return
*/
public String send(String context,String TOReceiver,String subject,Boolean ifattachment) {
logger.info("开始发邮件");
Boolean ispackage=false;//默认不打包
TO = TOReceiver;
TOS = TO.split(",");
SUBJECT =subject;
Properties props = new Properties();
props.put("mail.smtp.host", HOST);// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.auth", "true"); // 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
Session session = Session.getDefaultInstance(props);// 用props对象构建一个session
session.setDebug(true);
MimeMessage message = new MimeMessage(session);// 用session为参数定义消息对象
try {
message.setFrom(new InternetAddress(FROM));// 加载发件人地址
InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加载收件人地址
for (int i = 0; i < TOS.length; i++) {
sendTo[i] = new InternetAddress(TOS[i]);
}
message.addRecipients(Message.RecipientType.TO, sendTo);
message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));// 设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错
// message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@receive.com", "USER_FF", "UTF-8")); //Bcc: 密送(可选)
//message.setSubject(toChinese(SUBJECT));// 加载标题
message.setSubject(SUBJECT);// 加载标题
Multipart multipart = new MimeMultipart();// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
BodyPart contentPart = new MimeBodyPart();// 设置邮件的文本内容
contentPart.setText(context);
multipart.addBodyPart(contentPart);
// 判断是否添加附件
if (ifattachment) {
//在服务器路径AFFIX下,遍历所有文件
Enumeration<String> filesDir=null;
if (ispackage) {
//文件有打包路径的话去打包路径拿取打包文件添加到附件中
filesDir = FileUtils.readFilesDir(AFFIXZIP);
}else {
filesDir = FileUtils.readFilesDir(AFFIX);
}
if (filesDir != null) {
while (filesDir.hasMoreElements()) {
BodyPart messageBodyPart = new MimeBodyPart();
String fileName = filesDir.nextElement().toString();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));// 添加附件的内容
//messageBodyPart.setFileName(toChinese(source.getName()));
messageBodyPart.setFileName(source.getName());
//messageBodyPart.setFileName(toChn(source.getName()));
multipart.addBodyPart(messageBodyPart);
logger.info("添加附件成功");
}
}
}
message.setContent(multipart);// 将multipart对象放到message中
message.saveChanges(); // 保存邮件
Transport transport = session.getTransport("smtp");// 发送邮件
transport.connect(HOST, USER, PWD);// 连接服务器的邮箱
transport.sendMessage(message, message.getAllRecipients());// 把邮件发送出去
transport.close();// 关闭连接
if (ifattachment) {
FileUtils.delAllFile(AFFIX);
}
} catch (Exception e) {
logger.info("发送邮件失败");
e.printStackTrace();
throw new BaseException(ResponseEnum.RESPONSE_7.getCode(),ResponseEnum.RESPONSE_7.getMsg());
}
return ResponseEnum.RESPONSE_21.getCode();
}
public static String toChinese(String text) {
try {
text = MimeUtility.encodeText(new String(text.getBytes(), "GB2312"), "GB2312", "B");
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
public static String toChn(String text) {
try {
text = MimeUtility.encodeText(text);
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
public static void main(String[] args) {
new SendMailUtil().send("<a href=\"http://www.baidu.cn\">baidu</a>","text/html;charset=gb2312","284350956@qq.com","ceshi",false);
}
}