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;
?}
}