Spring Boot message

Learning objectives Quickly master the core logic of e-mail business and the daily service of enterprise e-mail. Quick...
1, Open mail service
2, Configure mail service
3, Send mail and attachments
Learning objectives
  • Quickly master the core logic of e-mail business and the daily service of enterprise e-mail.
Quick reference

Topic Reading: SpringBoot sermon series

Source code download: springboot-send-mail

— Hey Man,Don't forget to Star or Fork . —

Basic knowledge
  • What is SMTP?
    The full name of SMTP is simple mail transfer protocol (Simple Mail Transfer Protocol). It is a set of specifications used to transfer mail from source address to destination address. It controls the transfer mode of mail. SMTP authentication requires an account and password to log in to the server. Its design is to prevent users from being invaded by spam.

  • What is IMAP?
    The full name of IMAP is Internet Message Access Protocol (Internet Mail Access Protocol). IMAP allows you to obtain mail information and download mail from the mail server. Like POP, IMAP is a mail acquisition protocol.

  • What is POP3?
    The full name of POP3 is Post Office Protocol 3 (post office protocol). POP3 supports client-side remote management of server-side mail. POP3 is often used for "offline" mail processing, that is, the client is allowed to download the server mail, and then the mail on the server will be deleted. At present, many POP3 mail servers only provide the function of downloading mail, and the server itself does not delete mail. This is an improved version of POP3 protocol.

  • What are the differences between IMAP and POP3 protocols?
    The biggest difference between the two is that IMAP allows two-way communication, that is, the operations on the client will be fed back to the server. For example, the client will receive mail, mark read and other operations, and the server will synchronize these operations. Although the POP protocol also allows the client to download server mail, the operations on the client will not be synchronized to the server. For example, when the client receives or marks read mail, the server will not synchronize these operations.

Advanced knowledge
  • What are JavaMailSender and JavaMailSender impl?
    JavaMailSender and JavaMailSenderImpl are the interfaces and implementation classes of integrated mail services officially provided by Spring. They are famous for their simple and efficient design. At present, they are the mainstream tools for sending mail and integrating mail services at the Java back end.

  • How to send mail through JavaMailSenderImpl?
    It is very simple to directly inject JavaMailSenderImpl into the business class and call the send method to send mail. Simple messages can be sent through SimpleMailMessage, while complex messages (such as adding attachments) can be sent through MimeMessageHelper. For example:

@Autowired private JavaMailSenderImpl mailSender; public void sendMail() throws MessagingException { //Simple mail SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom("[email protected]"); simpleMailMessage.setTo("[email protected]"); simpleMailMessage.setSubject("Happy New Year"); simpleMailMessage.setText("Happy New Year!"); mailSender.send(simpleMailMessage); //Complex mail MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage); messageHelper.setFrom("[email protected]"); messageHelper.setTo("[email protected]"); messageHelper.setSubject("Happy New Year"); messageHelper.setText("Happy New Year!"); messageHelper.addInline("doge.gif", new File("xx/xx/doge.gif")); messageHelper.addAttachment("work.docx", new File("xx/xx/work.docx")); mailSender.send(mimeMessage); }
  • Why can JavaMailSenderImpl be used out of the box?
    The so-called out of the box is actually based on the official built-in automatic configuration. You can see from the source code that the mail automatic configuration class (MailSenderPropertiesConfiguration) provides a mail service instance (JavaMailSenderImpl) for the context. The specific source code is as follows:
@Configuration @ConditionalOnProperty(prefix = "spring.mail", name = "host") class MailSenderPropertiesConfiguration { private final MailProperties properties; MailSenderPropertiesConfiguration(MailProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean public JavaMailSenderImpl mailSender() { JavaMailSenderImpl sender = new JavaMailSenderImpl(); applyProperties(sender); return sender; }

MailProperties is the configuration information about the mail server. The specific source code is as follows:

@ConfigurationProperties(prefix = "spring.mail") public class MailProperties { private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private String host; private Integer port; private String username; private String password; private String protocol = "smtp"; private Charset defaultEncoding = DEFAULT_CHARSET; private Map<String, String> properties = new HashMap<>(); }
Using tutorials

1, Open mail service

Log in to Netease mailbox 163, open and check POP3/SMTP/IMAP service in settings, and then you will get an authorization code, which will be used as login authentication.

2, Configure mail service

First, let's pass Spring Initializr Create the project springboot send mail, as shown in the figure:

Then we introduce web, thymeleaf and spring boot starter mail into pom.xml. For example:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

Fill in the relevant configuration information according to the previously mentioned configuration item (MailProperties), where spring.mail.username indicates the login account authenticated when connecting to the mail server, which can be an ordinary mobile phone number or login account, not necessarily an email. In order to solve this problem, it is recommended to fill in the email sender, that is, the real email, at spring.mail. properties.from.

Then add the following configuration in application.yml:

spring: mail: host: smtp.163.com #SMTP server address username: socks #Login account password: 123456 #Login password (or authorization code) properties: from: [email protected] #Mail sender (i.e. real mailbox) thymeleaf: cache: false prefix: classpath:/views/ servlet: multipart: max-file-size: 10MB #Limit the size of a single file max-request-size: 50MB #Limit total requests

From the previous advanced knowledge, we know that before sending e-mail, we need to build SimpleMailMessage or MimeMessage e-mail information class to fill in e-mail title, e-mail content and other information, and finally submit it to JavaMailSenderImpl to send e-mail. This seems to be no problem and can achieve the set goal, but there will be a lot of scattered and repeated code in practical use, It is not easy to save mail to the database.

So how to send email gracefully? The details of building information and sending e-mail should be shielded. Whether simple or complex e-mail, e-mail can be sent through a unified API. For example: mailService.send(mailVo).

For example, through mail information class( MailVo )To save the message subject, message content and other information when sending the message:

package com.hehe.vo; public class MailVo { private String id;//Mail id private String from;//Mail sender private String to;//Mail recipients (multiple mailboxes are separated by commas ",") private String subject;//Mail subject private String text;//Mail content private Date sentDate;//Sending time private String cc;//CC (multiple mailboxes are separated by commas ",") private String bcc;//BCC (multiple mailboxes are separated by commas ",") private String status;//state private String error;//Error message @JsonIgnore private MultipartFile[] multipartFiles;//Mail attachment //Omit the get & set method }

3, Send mail and attachments

===========Next, let's formally introduce the core logic of sending e-mail=============

In addition to sending mail, it also includes operations such as detecting mail and saving mail, such as:

  • Check mail(); First, check the required items of mail recipient, mail subject and mail content. If it is empty, it will be rejected.

  • Send mail sendMimeMail(); Secondly, use MimeMessageHelper to parse MailVo and build MimeMessage to transmit mail.

  • Save the message sendMimeMail(); Finally, the mail is saved to the database to facilitate the statistics and tracking of mail problems.

The specific source code of mail service in this case is as follows:

package com.hehe.service; /** * Mail service */ @Service public class MailService { private Logger logger = LoggerFactory.getLogger(getClass());//Provide log class @Autowired private JavaMailSenderImpl mailSender;//Inject mail tool class /** * Send mail */ public MailVo sendMail(MailVo mailVo) { try { checkMail(mailVo); //1. Check email sendMimeMail(mailVo); //2. Send mail return saveMail(mailVo); //3. Save mail } catch (Exception e) { logger.error("Failed to send mail:", e);//Print error message mailVo.setStatus("fail"); mailVo.setError(e.getMessage()); return mailVo; } } //Detect mail information class private void checkMail(MailVo mailVo) { if (StringUtils.isEmpty(mailVo.getTo())) { throw new RuntimeException("Mail recipient cannot be empty"); } if (StringUtils.isEmpty(mailVo.getSubject())) { throw new RuntimeException("Message subject cannot be empty"); } if (StringUtils.isEmpty(mailVo.getText())) { throw new RuntimeException("Message content cannot be empty"); } } //Building complex mail information classes private void sendMimeMail(MailVo mailVo) { try { MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true indicates that complex types are supported mailVo.setFrom(getMailSendFrom());//Mail sender read from configuration item messageHelper.setFrom(mailVo.getFrom());//Mail sender messageHelper.setTo(mailVo.getTo().split(","));//Mail recipient messageHelper.setSubject(mailVo.getSubject());//Mail subject messageHelper.setText(mailVo.getText());//Mail content if (!StringUtils

12 November 2021, 03:34 | Views: 2435

Add new comment

For adding a comment, please log in
or create account

0 comments