Preparation 1. Introducing Dependencies
<!-- 发送邮件依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2. Configure the necessary properties in APPLICATION.YML
PS: here because the use of QQ mailbox, and QQ Mailbox Software Transceiver Service is closed by default, need to manually open
Access to email account settings
spring: mail: host: smtp.qq.com username: 邮箱用户名 password: 密码或验证码 properties: mail: smtp: auth: true starttls: enable: true required: true
3. Send a simple message
@Autowired private JavaMailSender mailSender; @Test public void sendSimpleMail() throws Exception { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("邮件发送方"); message.setTo("邮件接收方"); message.setSubject("主题"); message.setText("正文"); mailSender.send(message); }
4. Send template mail (using thymeleaf) 1. Introducing Thymeleaf Dependencies
<!-- 引入thymeleaf模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.0.0.RELEASE</version> </dependency>
2. Configure Thymeleaf
# thymeleaf 参数配置spring: thymeleaf: cache: true prefix: classpath:/templates/ suffix: .html encoding: UTF-8 servlet: content-type: text/html check-template-location: true enabled: true mode: HTML5
3. Writing a template
4. Writing the Sending method @Autowired private TemplateEngine templateEngine; @Autowired private JavaMailSender mailSender; public void sendTemplateMail() throws Exception{ MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setFrom("发送方"); helper.setTo("接收方"); helper.setSubject("主题"); Context context = new Context(); context.setVariable("username","name"); String emailContent = templateEngine.process("template",context); helper.setText(emailContent,true); mailSender.send(message); }
Springboot sending mail