Spring Boot email

Keywords: Java Spring Lombok github

How to use Spring Boot to send mail?

Spring Boot provides a starter: Spring Boot starter mail for sending mail.

Next, let's see how to send mail using Spring Boot.

 

1, Configure mailbox

Here we use 163 Netease email

1. Open SMTP service

2. Set / reset client authorization password

 

2, Coding implementation

1. Add dependency

1 <!--mail-->
2 <dependency>
3     <groupId>org.springframework.boot</groupId>
4     <artifactId>spring-boot-starter-mail</artifactId>
5 </dependency>

2. Write configuration

1 # mail
2 spring.mail.host=smtp.163.com
3 spring.mail.username=xxxxxx@163.com
4 spring.mail.password=xxxxxx
5 spring.mail.from=xxxxxx@163.com
6 spring.mail.properties.mail.smtp.auth=true
7 spring.mail.properties.mail.smtp.starttls.enable=true
8 spring.mail.properties.mail.smtp.starttls.required=true

3. Write email sending entity class

 1 package com.alanlee.dto;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Getter;
 5 import lombok.NoArgsConstructor;
 6 import lombok.Setter;
 7 
 8 import javax.validation.constraints.NotBlank;
 9 import javax.validation.constraints.Pattern;
10 
11 @Getter
12 @Setter
13 @NoArgsConstructor
14 @AllArgsConstructor
15 public class Mail {
16 
17     @Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", message = "Incorrect mailbox format")
18     private String to;
19 
20     @NotBlank(message = "Title cannot be empty")
21     private String title;
22 
23     @NotBlank(message = "Body cannot be empty")
24     private String content;
25 
26     private String msgId;// news id
27 
28 }

4. Write email sending tool class

 1 package com.alanlee.util;
 2 
 3 import com.alanlee.dto.Mail;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.beans.factory.annotation.Value;
 7 import org.springframework.core.io.FileSystemResource;
 8 import org.springframework.mail.MailException;
 9 import org.springframework.mail.SimpleMailMessage;
10 import org.springframework.mail.javamail.JavaMailSender;
11 import org.springframework.mail.javamail.MimeMessageHelper;
12 import org.springframework.stereotype.Component;
13 
14 import javax.mail.internet.MimeMessage;
15 import java.io.File;
16 
17 /**
18  * Mail sending tool class
19  *
20  * @author AlanLee
21  */
22 @Component
23 @Slf4j
24 public class MailUtil {
25 
26     /**
27      * From
28      */
29     @Value("${spring.mail.from}")
30     private String from;
31 
32     @Autowired
33     private JavaMailSender mailSender;
34 
35     /**
36      * Send simple mail
37      *
38      * @param mail
39      */
40     public boolean send(Mail mail) {
41         String to = mail.getTo();// Target mailbox
42         String title = mail.getTitle();// Message title
43         String content = mail.getContent();// Message body
44 
45         SimpleMailMessage message = new SimpleMailMessage();
46         message.setFrom(from);
47         message.setTo(to);
48         message.setSubject(title);
49         message.setText(content);
50 
51         try {
52             mailSender.send(message);
53             log.info("Mail sent successfully");
54             return true;
55         } catch (MailException e) {
56             log.error("Failed to send mail, to: {}, title: {}", to, title, e);
57             return false;
58         }
59     }
60 
61     /**
62      * Send attachment email (no call for now, improve business logic later)
63      *
64      * @param mail mail
65      * @param file enclosure
66      */
67     public boolean sendAttachment(Mail mail, File file) {
68         String to = mail.getTo();
69         String title = mail.getTitle();
70         String content = mail.getContent();
71 
72         MimeMessage message = mailSender.createMimeMessage();
73         try {
74             MimeMessageHelper helper = new MimeMessageHelper(message, true);
75             helper.setFrom(from);
76             helper.setTo(to);
77             helper.setSubject(title);
78             helper.setText(content);
79             FileSystemResource resource = new FileSystemResource(file);
80             String fileName = file.getName();
81             helper.addAttachment(fileName, resource);
82             mailSender.send(message);
83             log.info("Attachment email sent successfully");
84             return true;
85         } catch (Exception e) {
86             log.error("Failed to send attachment mail, to: {}, title: {}", to, title, e);
87             return false;
88         }
89     }
90 
91 }

5. Finally, write a main method and so on. Call to test whether it can be sent successfully. Do it yourself is the king.

 

Conclusion: in the most ordinary life of humility and hard work, one day you will stand in the brightest place, live as you once desired.

 

Buddhist blogger: Alan Lee

Blog address: http://www.cnblogs.com/AlanLee

GitHub address: https://github.com/AlanLee-Java

This article comes from blog park. Welcome to join blog park.

Posted by ComputerChip on Sun, 17 May 2020 08:10:16 -0700