在 pom.xml 文件中添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
使用 163 邮箱发送邮件,在 application.properties 文件中添加配置:
#server server.port=80 #spring.mail spring.mail.host=smtp.163.com spring.mail.username=smileorsilence@163.com spring.mail.password=授权码 spring.mail.receiver=收件人 #spring.mail.properties spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.timeout=30000 #spring.thymeleaf spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=LEGACYHTML5 spring.thymeleaf.encoding=utf-8 spring.thymeleaf.cache=false
编写配置类:
package com.springboot.config.mail; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; /** * @author smileorsilence * @date 2018/04/10 */ @Data @ConfigurationProperties(prefix = "spring.mail") public class MailProperties { /** * 邮件服务器主机名 * 163邮箱 : smtp.163.com * QQ邮箱 : smtp.qq.com */ private String host; /** * 邮件服务器端口号 * 默认25 */ private Integer port = 25; /** * 邮箱用户名 */ private String username; /** * 邮箱第三方授权码 */ private String password; /** * 邮件传输协议 * 默认smtp */ private String protocol = "smtp"; /** * 邮件编码 * 默认UTF-8 */ private Charset charset = Charset.forName("UTF-8"); private Map<String, String> properties; public MailProperties() { this.properties = new HashMap(); } }
package com.springboot.config.mail; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Properties; /** * @author smileorsilence * @date 2018/04/10 */ @Slf4j @Configuration @EnableConfigurationProperties(MailProperties.class) public class MailConfiguration { @Autowired private MailProperties mailProperties; @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(mailProperties.getHost()); javaMailSender.setPort(mailProperties.getPort().intValue()); javaMailSender.setUsername(mailProperties.getUsername()); javaMailSender.setPassword(mailProperties.getPassword()); javaMailSender.setProtocol(mailProperties.getProtocol()); javaMailSender.setDefaultEncoding(mailProperties.getCharset().name()); Properties properties = new Properties(); if (!mailProperties.getProperties().isEmpty()) { properties.putAll(mailProperties.getProperties()); } javaMailSender.setJavaMailProperties(properties); log.info("mailProperties : {}", mailProperties); return javaMailSender; } }
编写Service接口:
package com.springboot.service; /** * @author smileorsilence * @date 2018/04/10 */ public interface MailService { void sendSimpleMail(String to, String subject, String content); void sendAttachmentMail(String to, String subject, String content, String fileName); void sendTemplateMail(String to, String subject, String templateName); }
编写Service实现类:
package com.springboot.service.impl; import com.springboot.service.MailService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; /** * @author smileorsilence * @date 2018/01/24 */ @Slf4j @Service public class MailServiceImpl implements MailService { @Autowired private JavaMailSender javaMailSender; @Autowired private SpringTemplateEngine templateEngine; /** * 图片路径 */ private static final String IMAGE_PATH = "static/images/"; /** * 邮件模板路径 */ private static final String TEMPLATE_PATH = "mail/"; @Value("${spring.mail.username}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { log.info("{} sendSimpleMail to {}, subject : {}, content : {}", from, to, subject, content); SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); log.info("{} sendSimpleMail begin", from); try { javaMailSender.send(message); } catch (MailException e) { log.warn("sendSimpleMail MailException : {}", e.getMessage()); } log.info("{} sendSimpleMail finish", from); } @Override public void sendAttachmentMail(String to, String subject, String content, String imageName) { log.info("{} sendAttachmentMail to {}, subject : {}, content : {}, imageName : {}", from, to, subject, content, imageName); MimeMessage message = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content); // File image = new File(IMAGE_PATH + imageName); ClassPathResource image = new ClassPathResource(IMAGE_PATH + imageName); helper.addAttachment(imageName, image); } catch (MessagingException e) { log.warn("sendAttachmentMail MessagingException : {}", e.getMessage()); } log.info("{} sendAttachmentMail begin", from); try { javaMailSender.send(message); } catch (MailException e) { log.warn("sendAttachmentMail MailException : {}", e.getMessage()); } log.info("{} sendAttachmentMail finish", from); } @Override public void sendTemplateMail(String to, String subject, String templateName) { log.info("{} sendTemplateMail to {}, subject : {}, templateName : {}", from, to, subject, templateName); MimeMessage message = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); // ClassPathResource backgroundImage = new ClassPathResource(IMAGE_PATH + "peachblossom.jpg"); // helper.addInline("backgroundImage", backgroundImage); Context context = new Context(); context.setVariable("receiver", to); String content = templateEngine.process(TEMPLATE_PATH + templateName, context); helper.setText(content); } catch (MessagingException e) { log.warn("sendTemplateMail MessagingException : {}", e.getMessage()); } log.info("{} sendTemplateMail begin", from); try { javaMailSender.send(message); } catch (MailException e) { log.warn("sendTemplateMail MailException : {}", e.getMessage()); } log.info("{} sendTemplateMail finish", from); } }
编写Junit单元测试:
package com.springboot.service.impl; import com.springboot.service.MailService; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author smileorsilence * @date 2018/04/10 */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class MailServiceImplTest { @Autowired private MailService mailService; @Value("${spring.mail.receiver}") private String to; @Test public void sendSimpleMail() throws Exception { String subject = "sendSimpleMail"; String content = "更无柳絮因风起,唯有葵花向日倾"; mailService.sendSimpleMail(to, subject, content); log.info("test sendSimpleMail to {}", to); } @Test public void sendAttachmentMail() throws Exception { String subject = "sendAttachmentMail"; String content = "况是青春日将暮,桃花乱落如红雨"; mailService.sendAttachmentMail(to, subject, content, "peachblossom.jpg"); log.info("test sendAttachmentMail to {}", to); } @Test public void sendTemplateMail() throws Exception { String subject = "sendTemplateMail"; String templateName = "mail"; mailService.sendTemplateMail(to, subject, templateName); log.info("test sendTemplateMail to {}", to); } }
登录163邮箱并启用授权码:
Spring Boot 学习笔记 6 : spring-boot-starter-mail
最新推荐文章于 2024-05-30 10:31:44 发布