5. springboot is simple and elegant to realize mail service

Preface

Sprboot's project has not been updated for half a month since it was put down. Finally, I can write happily when I am free.
Before we configure mybatis with multiple data sources, we need to do an email service. For example, when you register, you need to enter a validation code to verify. This validation code can be sent by mail. Of course, most of the validation codes nowadays are through short messages, and single mail is sometimes essential. So our spring scaffolding is still building mail services. The next article will integrate SMS services.
All right, back to the truth. Setting up a mail service without contact may be very troublesome or the stand-alone environment test environment can not be achieved. I don't think there is any mail service. In fact, if we use it personally, it can be done. QQ mailbox, Netease mailbox can be. I use QQ mailbox here. There are many related courses on the Internet.

Mailbox Server Readiness

Log in to QQ mailbox and click Settings - > Account to find this picture below.

POP3/SMTP services need to be opened. When this is enabled, a secret key is generated. This secret key will be used later in the project. Take a small book and write it down.

Adding dependencies and configurations

The mailbox is ready. Let's start our project.
First add dependencies to the pom.xml file

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

Then add the configuration in the application.proteries file and change it to your own mailbox. password is the secret key just generated. The server address of QQ mailbox is smtp.qq.com. Netease can be searched.

spring.mail.host=smtp.qq.com
spring.mail.username=1186154608@qq.com
spring.mail.password=abcdefgqazqaz
spring.mail.default-encoding=UTF-8

mail.from=1186154608@qq.com

Service level

Once the configuration information is ready, we can use it. We have not touched on the database for the time being, so we write the Service layer and the controller layer directly.
Create a MailService and MailService Impl under the service package

Code in MailService Impl

@Service
@Slf4j
public class MailServiceImpl implements MailService{
    @Autowired
    private JavaMailSender mailSender;
    @Value("${mail.from}")
    private String mailFrom;
    @Override
    public void sendSimpleMail(String mailTo) {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(mailTo);
        message.setSubject("simple mail");
        message.setText("hello world");
        mailSender.send(message);
        log.info("Mail has been sent");
    }

}

Here we will test it to see if the mail can be sent. mailFrom is the sender and mailTo is the recipient. message.setSubject() sets the mail topic. message.setText() sets the message content.
mailSender.send(message) is to send short messages.

# controller layer
Let's create a MailController class. The code is as follows:
```
@RestController
@RequestMapping("/mail")
public class MailController {
@Autowired
private MailService mailService;

@RequestMapping(value = "/send",method = RequestMethod.GET)
public String sendMail(@RequestParam(value = "userName")String userName){
    mailService.sendSimpleMail(userName);
    return "success";
}

}
```
You can see just one sending interface. It's very simple, just pass the parameters to the recipient's mailbox.

Test of test
So far, demo of our mail service has been built. Let's test it next. We started the project. Then adjust the interface.
http://localhost:9090/zlflovemm/mail/send?userName=1303123974@qq.com

The reminder has been sent successfully. Let's go into the mailbox and see how we send it. You can see that the delivery was successful. So it shows that our mail service has been successfully built.

So now it seems that spring boot integration mail service is very simple, configure mail server, you can use it directly.

Sending attachments

Sometimes we send email not only to send content, but also to send attachments. How can we do that? In fact, it's very simple. Those configurations remain unchanged. We are in the service layer. Write a sendMail method. as follows

@Override
    public void sendMail(String mailTo) {
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(mailTo);
            helper.setSubject("simple mail");
            helper.setText("hello world", true);
            FileSystemResource file = new FileSystemResource(new File("E:\\myself\\test.xls"));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("Mail has been sent");
        } catch (MessagingException e) {
            log.error("{}",e);
        }
    }

You can see that it's a little different from when we started testing. Here first

MimeMessage message=mailSender.createMimeMessage();

Mimemessage is more powerful than SimpleMailMessage. It can send attachments or convert content to html format. So MimeMessage is usually used in practice.
In addition, you need to use MimeMessageHelper to send attachments. MimeMessageHelper assists MimeMessage.

helper.setFrom(mailFrom);
helper.setTo(mailTo);
helper.setSubject("simple mail");
helper.setText("hello world", true);

These are the same as before, sender, recipient, theme, content.
helper.addAttachment() is to add attachments.

Okay, let's test it next. You can see that the mail sent has attachments. Prove no problem.

Off the coast

All right, so much to say, the code of the project is synchronized to github today.
Github address: https://github.com/QuellanAn/zlflovemm

Follow-up refueling

Welcome to pay attention to the personal public number "programmers love yogurt"

Share various learning materials, including java, linux, big data, etc. The information includes video documents and source code, and shares my own and high-quality technical blog posts.

If you like to remember to pay attention to and share yo

This article by the blog article multiple platform OpenWrite Release!

Keywords: Java Spring github Mybatis xml

Added by Pjack125 on Fri, 11 Oct 2019 13:41:06 +0300