您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用velocity實(shí)現(xiàn)自定義模板發(fā)送郵件,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
郵件發(fā)送,可以自定義模板,使用velocity或者thymeleaf均可。
本文以velocity為例:
package cn.xing.util; import org.apache.velocity.app.VelocityEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.internet.MimeUtility; import org.springframework.ui.velocity.VelocityEngineUtils; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Map; import java.util.Properties; @Service public class MailSender implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(MailSender.class); private JavaMailSenderImpl mailSender; @Autowired private VelocityEngine velocityEngine; public boolean sendWithHTMLTemplate(String to, String subject, String template, Map<String, Object> model) { try { String nick = MimeUtility.encodeText("??椭屑?jí)課"); InternetAddress from = new InternetAddress(nick + "<course@nowcoder.com>"); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage); //設(shè)置郵件模板 String result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, "UTF-8", model); mimeMessageHelper.setTo(to); mimeMessageHelper.setFrom(from); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(result, true); mailSender.send(mimeMessage); return true; } catch (Exception e) { logger.error("發(fā)送郵件失敗" + e.getMessage()); return false; } } @Override public void afterPropertiesSet() throws Exception { mailSender = new JavaMailSenderImpl(); mailSender.setUsername("course@nowcoder.com"); mailSender.setPassword("NKnk66"); mailSender.setHost("smtp.exmail.qq.com"); mailSender.setPort(465); mailSender.setProtocol("smtps"); mailSender.setDefaultEncoding("utf8"); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.ssl.enable", true); mailSender.setJavaMailProperties(javaMailProperties); } }
使用:
@Autowired MailSender mailSender; public void testmail() { Map<String, Object> map = new HashMap<String, Object>(); map.put("username","我是郵件內(nèi)容呀"); //mails/welcome.html是templates里的html模板 mailSender.sendWithHTMLTemplate("123123@163.com", "登陸異常", "mails/welcome.html", map); }
Thymeleaf用法類(lèi)似。
以上是“如何使用velocity實(shí)現(xiàn)自定義模板發(fā)送郵件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。