controller层
//发送邮件
@RequestMapping("/sendEmail")
public void sendEmail(HttpServletRequest request,HttpServletResponse response){
//建立map用于回传参数
Map<String, Object> returnMap=new HashMap<>();
try {
//解析request请求,获取参数
String targetAddress = request.getParameter("targetAddress");
String title = request.getParameter("title");
String content = request.getParameter("content");
//调用发送邮件的工具
SendEmailToUser.sendEmailInfoToUser(targetAddress,title,content);
returnMap.put("isSuccess", true);//发送成功
} catch (Exception e) {
returnMap.put("isSuccess", false);//发送失败
e.printStackTrace();
}
//回传
Gson gson=new Gson();
String responseContent = gson.toJson(returnMap);
this.flushResponse(response, responseContent);
}
}
/*
* 传送邮件
*/
public class SendEmailToUser {
//传送邮件的方法
public static void sendEmailInfoToUser(String targetAddress, String title, String content) throws Exception{
//与服务器建立连接
Properties properties=new Properties();
//设置服务器的名字
properties.setProperty("mail.host", "smtp.163.com");
//设置邮件的传输协议
properties.setProperty("mail.transport.protocol", "smtp");
//设置是否验证服务器的用户名和密码
properties.setProperty("mail.smtp.auth", "true");
// 创建客户端与邮箱服务器的Session对象( Session用于收集JavaMail运行过程中的环境信息)
Session session = Session.getInstance(properties);
//通过session得到传输的transport对象
Transport transport = session.getTransport();
// 使用用户名密码连接上邮箱服务器,此处的密码需要到邮箱开启服务设置
transport.connect("smtp.163.com", "chenzetao6666", "chenzetao6666");
//创建邮件对象
Message message=creatMessage(targetAddress,title,content,session);
//发送邮件----essage.getAllRecipients()获取所有的收件人
transport.sendMessage(message, message.getAllRecipients());
transport.close();//关闭传送
}
private static Message creatMessage(String targetAddress, String title, String content, Session session) throws Exception{
//通过message的子类mimeMessage创建对象
Message message=new MimeMessage(session);
//设置邮件的发送人
message.setFrom(new InternetAddress("chenzetao6666@163.com"));
//设置邮件的接收人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(targetAddress));
//邮件的标题
message.setSubject(title);
//邮件的内容
message.setContent(content,"text/html;charset=UTF-8");
return message;
}
}