程式碼珍藏之傳送郵件
/**
* 傳送重置密碼郵件
* @return
*/
@RequestMapping(params="sendResetPwdMail")
@ResponseBody
public AjaxJson sendResetPwdMail(String email,HttpServletRequest request){
AjaxJson ajaxJson = new AjaxJson();
try {
if(StringUtils.isEmpty(email)){
ajaxJson.setSuccess(false);
ajaxJson.setMsg("郵件地址不能為空");
return ajaxJson;
}
TSUser user = systemService.findUniqueByProperty(TSUser.class, "email", email);
if(user == null){
ajaxJson.setSuccess(false);
ajaxJson.setMsg("使用者名稱對應的使用者資訊不存在");
return ajaxJson;
}
String hql = "from TSPasswordResetkey bean where bean.username = ? and bean.isReset = 0 order by bean.createDate desc limit 1";
List<TSPasswordResetkey> resetKeyList = systemService.findHql(hql,user.getUserName());
if(resetKeyList != null && !resetKeyList.isEmpty()){
TSPasswordResetkey resetKey = resetKeyList.get(0);
Date now = new Date();
if(resetKey.getEmail().equals(email) && (now.getTime() - resetKey.getCreateDate().getTime()) < (1000*60*60*3 - 1000*60*5)){
ajaxJson.setSuccess(false);
ajaxJson.setMsg("已傳送重置密碼郵件,請稍候再次嘗試傳送");
return ajaxJson;
}
}
TSPasswordResetkey passwordResetKey = new TSPasswordResetkey();
passwordResetKey.setEmail(email);
passwordResetKey.setUsername(user.getUserName());
passwordResetKey.setCreateDate(new Date());
passwordResetKey.setIsReset(0);
userService.save(passwordResetKey);
String content = ResourceUtil.getConfigByName("resetpwd.mail.content");
if(content.indexOf("${username}") > -1){
content = content.replace("${username}", user.getUserName());
}
String url = request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath() +"/loginController.do?goResetPwd&key=" + passwordResetKey.getId();
//配置郵件模板引數
Map<String, Object> mailConfig = new HashMap<String, Object>();
mailConfig.put("title", ResourceUtil.getConfigByName("resetpwd.mail.title"));
mailConfig.put("content",content);
mailConfig.put("url",url);
mailConfig.put("commentUrl","http://www.jeecg.org");
String mailContent = new FreemarkerHelper().parseTemplate("export/mail/password_reset.ftl", mailConfig);
MailUtil.sendEmail(ResourceUtil.getConfigByName("mail.smtpHost"), email,"郵箱重置密碼", mailContent, ResourceUtil.getConfigByName("mail.sender"), ResourceUtil.getConfigByName("mail.user"), ResourceUtil.getConfigByName("mail.pwd"));
ajaxJson.setMsg("成功傳送密碼重置郵件");
} catch (Exception e) {
if("javax.mail.AuthenticationFailedException".equals(e.getClass().getName())){
ajaxJson.setSuccess(false);
ajaxJson.setMsg("傳送郵件失敗:郵箱賬號資訊設定錯誤" );
log.error("重置密碼傳送郵件失敗:郵箱賬號資訊設定錯誤",e);
}else{
ajaxJson.setSuccess(false);
ajaxJson.setMsg("傳送郵件失敗:" + e.getMessage());
log.error("傳送郵件失敗:" + e.getMessage(),e);
}
}
return ajaxJson;
}
/**
* 傳送電子郵件
*
* @param smtpHost
* 發信主機
* @param receiver
* 郵件接收者
* @param title
* 郵件的標題
* @param content
* 郵件的內容
* @param sender
* 郵件傳送者
* @param user
* 傳送者郵箱使用者名稱
* @param pwd
* 傳送者郵箱密碼
* @throws MessagingException
*/
public static void sendEmail(String smtpHost, String receiver,
String title, String content, String sender, String user, String pwd) throws MessagingException
{
Properties props = new Properties();
props.put("mail.host", smtpHost);
props.put("mail.transport.protocol", "smtp");
// props.put("mail.smtp.host",smtpHost);//發信的主機,這裡要把您的域名的SMTP指向正確的郵件伺服器上,這裡一般不要動!
props.put("mail.smtp.auth", "true");
Session s = Session.getDefaultInstance(props);
s.setDebug(true);
MimeMessage message = new MimeMessage(s);
// 給訊息物件設定發件人/收件人/主題/發信時間
// 發件人的郵箱
InternetAddress from = new InternetAddress(sender);
message.setFrom(from);
InternetAddress to = new InternetAddress(receiver);
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(title);
message.setSentDate(new Date());
// 給訊息物件設定內容
BodyPart mdp = new MimeBodyPart();// 新建一個存放信件內容的BodyPart物件
mdp.setContent(content, "text/html;charset=gb2312");// 給BodyPart物件設定內容和格式/編碼方式防止郵件出現亂碼
Multipart mm = new MimeMultipart();// 新建一個MimeMultipart物件用來存放BodyPart對
// 象(事實上可以存放多個)
mm.addBodyPart(mdp);// 將BodyPart加入到MimeMultipart物件中(可以加入多個BodyPart)
message.setContent(mm);// 把mm作為訊息物件的內容
message.saveChanges();
Transport transport = s.getTransport("smtp");
transport.connect(smtpHost, user, pwd);// 設定發郵件的閘道器,發信的帳戶和密碼,這裡修改為您自己用的
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
配置:
mail.smtpHost=smtp.qq.com
[email protected]
[email protected]
mail.pwd=*********