发送邮件的封装类:

package com.email;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.MimeMessageHelper; public class Email {
public MimeMessage message;
public MimeMessageHelper creatEmail(String host, String port, String user, String pw) throws MessagingException{
// 创建Properties 类用于记录邮箱的一些属性
final Properties props = new Properties();
// 表示SMTP发送邮件,必须进行身份验证
props.put("mail.smtp.auth", "true");
//开启ttl加密
props.put("mail.smtp.starttls.enable", "true");
//此处填写SMTP服务器
props.put("mail.smtp.host", host);
//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
props.put("mail.smtp.port", port);
// 此处填写你的账号
props.put("mail.user", user);
// 此处的密码就是前面说的16位STMP口令
props.put("mail.password", pw); // 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
message = new MimeMessage(mailSession);
MimeMessageHelper helper = null;
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
try {
helper = new MimeMessageHelper(message,true,"utf-8");
helper.setFrom(form);
} catch (MessagingException e) {
e.printStackTrace();
}
return helper;
}
}

调用方法:发送邮件

@RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
@ResponseBody
public ArrayList sendEmail(@RequestBody HashMap body) throws MessagingException{
Email email = new Email();
MimeMessageHelper msgHelper = email.creatEmail("邮箱发信服务器地址", "端口", "发件邮箱", "密码");
msgHelper.setTo((String)body.get("toEmail"));
msgHelper.setSubject("主题");
msgHelper.setText("内容");
Transport.send(email.message);
ArrayList ls = new ArrayList();
ls.add("OK");
return ls;
}
05-11 22:56