Hello大家好,本章我们添加系统发送邮件功能 。有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢
本章我们介绍发送普通邮件,发送附件,发送模板邮件等
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
打开application.properties
添加如下配置
spring.mail.protocol=smtp spring.mail.host=smtp.chuchenkj.xyz #这里换成自己的邮箱类型 例如qq邮箱就写smtp.qq.com spring.mail.port=25 spring.mail.smtpAuth=true spring.mail.smtpStarttlsEnable=true spring.mail.smtpSslTrust=smtp.chuchenkj.xyz #这里换成自己的邮箱类型 例如qq邮箱就写smtp.qq.com spring.mail.username=chuchenkf@chuchenkj.xyz #这里换成自己的邮箱账号 spring.mail.password=**************** #这里换成自己的邮箱密码或授权码 授权码获取可以百度
package com.example.demo.model; import java.util.Map; public class Mail { /** * 发给多个人 */ private String[] to; /** * 抄送 */ private String[] cc; /** * 邮件标题 */ private String subject; /** * 邮件内容 简单文本 和附件邮件必填 其余的不需要 */ private String text; /** * 模板需要的数据 发送模板邮件必填 */ private Map<String,String> templateModel; /** * 选用哪个模板 发送模板邮件必填 */ private String templateName; public String[] getTo() { return to; } public void setTo(String[] to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Map<String, String> getTemplateModel() { return templateModel; } public void setTemplateModel(Map<String, String> templateModel) { this.templateModel = templateModel; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public String[] getCc() { return cc; } public void setCc(String[] cc) { this.cc = cc; } }
创建core→constant→MailConstant
package com.example.demo.core.constant; public class MailConstant { /** * 注册的模板名称 */ public static final String RETGISTEREMPLATE = "register"; /** * 模板存放的路径 */ public static final String TEMPLATEPATH = "src/test/java/resources/template/mail"; }
MailService
package com.example.demo.service; import com.example.demo.model.Mail; import javax.servlet.http.HttpServletRequest; public interface MailService { /** * 发送简单邮件 * @param mail */ void sendSimpleMail(Mail mail); /** * 发送带附件的邮件 * @param mail * @param request */ void sendAttachmentsMail(Mail mail, HttpServletRequest request); /** * 发送静态资源 一张照片 * @param mail * @throws Exception */ void sendInlineMail(Mail mail) throws Exception; /** * 发送模板邮件 * @param mail */ void sendTemplateMail(Mail mail); }
MailServiceImpl
package com.example.demo.service.impl; import com.example.demo.core.constant.MailConstant; import com.example.demo.core.utils.UploadActionUtil; import com.example.demo.model.Mail; import com.example.demo.service.MailService; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import javax.annotation.Resource; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.List; @Service public class MailServiceImpl implements MailService { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); @Resource @Qualifier("javaMailSender") private JavaMailSender mailSender; @Value("${spring.mail.username}") private String from; @Resource private FreeMarkerConfigurer freeMarkerConfigurer; /** * 发送简单邮件 */ @Override public void sendSimpleMail(Mail mail){ SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(mail.getTo()); message.setSubject(mail.getSubject()); message.setText(mail.getText()); message.setCc(mail.getCc()); mailSender.send(message); } /** * 发送附件 * * @throws Exception */ @Override public void sendAttachmentsMail(Mail mail,HttpServletRequest request){ try{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(from); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); helper.setText(mail.getText()); List<String> list = UploadActionUtil.uploadFile(request); for (int i = 1,length = list.size();i<=length;i++) { String fileName = list.get(i-1); String fileTyps = fileName.substring(fileName.lastIndexOf(".")); FileSystemResource file = new FileSystemResource(new File(fileName)); helper.addAttachment("附件-"+i+fileTyps, file); } mailSender.send(mimeMessage); }catch (Exception e){ e.printStackTrace(); } } /** * 发送静态资源 一张照片 * @param mail * @throws Exception */ @Override public void sendInlineMail(Mail mail){ try{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(from); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); helper.setText("<html><body><img src=/"cid:chuchen/" ></body></html>", true); FileSystemResource file = new FileSystemResource(new File("C://Users//Administrator//Desktop//设计图//已完成//微信图片_20180323135358.png")); // addInline函数中资源名称chuchen需要与正文中cid:chuchen对应起来 helper.addInline("chuchen", file); mailSender.send(mimeMessage); }catch (Exception e){ logger.error("发送邮件发生异常"); } } /** * 发送模板邮件 * @param mail */ @Override public void sendTemplateMail(Mail mail){ MimeMessage message = null; try { message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); //读取 html 模板 freemarker.template.Configuration cfg = getConfiguration(); Template template = cfg.getTemplate(mail.getTemplateName()+".ftl"); String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mail.getTemplateModel()); helper.setText(html, true); } catch (Exception e) { e.printStackTrace(); } mailSender.send(message); } private static freemarker.template.Configuration getConfiguration() throws IOException { freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(MailConstant.TEMPLATEPATH)); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); return cfg; } }
这里我们创建一个注册的模板,其他模板大家可自行创建
在src/test/java/resources/template/mail目录下创建 register.ftl
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf8"> </head> <body> <div><span>尊敬的</span>${to}:</div> <div> <span>欢迎您加入初晨,您的验证码为: <span style="color: red;">${identifyingCode}</span> </span> </div> <span style="margin-top: 100px">初晨科技</span> </body> </html>
看到这里,可能有的同学就很熟悉,对,这就是 自动生成Service,Controller 这篇文章里用到的方法
package com.example.demo.controller; import com.example.demo.core.constant.MailConstant; import com.example.demo.core.ret.RetResponse; import com.example.demo.core.ret.RetResult; import com.example.demo.core.utils.ApplicationUtils; import com.example.demo.model.Mail; import com.example.demo.service.MailService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/mail") public class MailController { @Resource private MailService mailService; /** * 发送注册验证码 * @param mail * @return 验证码 * @throws Exception */ @PostMapping("/sendTemplateMail") public RetResult<String> sendTemplateMail(Mail mail) throws Exception { String identifyingCode = ApplicationUtils.getNumStringRandom(6); mail.setSubject("欢迎注册初晨"); mail.setTemplateName(MailConstant.RETGISTEREMPLATE); Map<String,String> map = new HashMap<>(); map.put("identifyingCode",identifyingCode); map.put("to",mail.getTo()[0]); mail.setTemplateModel(map); mailService.sendTemplateMail(mail); return RetResponse.makeOKRsp(identifyingCode); } @PostMapping("/sendAttachmentsMail") public RetResult<String> sendAttachmentsMail(Mail mail,HttpServletRequest request) throws Exception { mail.setSubject("测试附件"); mailService.sendAttachmentsMail(mail, request); return RetResponse.makeOKRsp(); } }
输入localhost:8080/mail/sendTemplateMail
打开邮箱
输入localhost:8080/mail/sendAttachmentsMail
ok,成功
gitee.com/beany/mySpr…
写文章不易,如对您有帮助,请帮忙点下star
添加系统发送邮件功能已完成,后续功能接下来陆续更新,有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢大家。