Web mail is a very useful feature, such as captcha, notifications and so on. Sending emails using Spring Boot is actually quite simple.

1, configuration,

Start by adding dependencies to the project pom.xml file:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Copy the code

Then open the Spring Boot configuration file application.properties and add the mail configuration:

Mail. host= SMTP server spring.mail.username= your email account spring.mail.password= email authorization code spring.mail.default-encoding=UTF-8Copy the code

And there you are!

If the SMTP service is enabled on your email address, take email address 163 as an example:

Open any one, and then follow the instructions, finally will get an authorization code, it is recommended to copy to a text document to write down, this page can also see the SMTP address, copy to the configuration inside:

2. Send a simple text email

Use @AutoWired to automatically inject a JavaMailSender object into a class that needs to call mail sending. Then create an instance of SimpleMailMessage and send it.

@Value("${spring.mail.username}") private String sender; @Autowired private JavaMailSender mailSender; public void sendNotifyMail(String email, String title, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(sender); message.setTo(email); message.setSubject(title); message.setText(text); try { mailSender.send(message); } catch (Exception e) { e.printStackTrace(); }}Copy the code

The sender variable above uses the @Value annotation to inject the configured email Value, because the sender email also needs to be written in the Java program when sending the email, so it’s convenient to inject the Value of the configuration file instead of writing the email address again.

And there’s a method called sendNotifyMail, which is how to send an email. Simply inject the JavaMailSender object, create a SimpleMailMessage instance, and specify the sender, recipient, subject, and content of the message. Finally, call the JavaMailSender instance’s Send method to send the SimpleMailMessage instance.

3. The problem that emails cannot be sent after Spring Boot is configured to Ali Cloud is solved

I tested sending email in local development, but it didn’t work on Ali Cloud. According to the data checked, mails are sent through port 25 by default, which is disabled by default in Aliyun for security reasons. Therefore, encrypted port 465 needs to be configured.

We just need to add the following configuration based on the above configuration file:

spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
Copy the code