Five, springboot simple elegance is achieved Mail Service

Foreword

spring boot project put down a small half a month has not been updated, you can finally retired and sit happy then write it.
Before we configured mybatis multiple data sources, then we need to do a mail service. For example, when you register, you need to enter a verification code to verify. This code can be sent via e-mail. Of course, now mostly a verification code via text message, a single message sometimes is also essential. So our spring frame scaffolding or mail service will also build up. The next SMS service will also be integrated in.
well, let's get back to business. Set up e-mail service is not in contact with may feel cumbersome or stand-alone environment test environment can not be achieved. I feel no mail service. In fact, our personal use, it can be done. qq mailbox, NetEase mailbox you can. I used here is the QQ mailbox. There are many online tutorials related.

Mailbox server ready

QQ-mail login, click Settings -> Account can be found in the following figure.

file

We need to open POP3 / SMTP services. After the opening of this, it will generate a secret key. This will be our secret key will be used in the project. Take the little book down haha.

Adding dependencies and configuration

E-mail is ready, we started our project now.
First, add a dependency in pom.xml file

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

Then add in application.proteries configuration file, into your mailbox. password is the secret key just generated. QQ-mail server address is: smtp.qq.com. NetEase you can search it.

spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=abcdefgqazqaz
spring.mail.default-encoding=UTF-8

[email protected]

file

Service Layer

After the configuration information is good, since we can use it. Here we do not relate to the database, write directly Service layer and controller layer.
Create a MailService and MailServiceImpl in the service pack

file

MailServiceImpl code

@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("邮件已经发送");
    }

}

Here we take a simple test to see e-mail can not be sent. mailFrom the sender, mailTo the recipient. message.setSubject () to set the message subject. message.setText () to set the message content.
mailSender.send (message) is to send text messages.

# Controller layer
we created a MailController class. Code is as follows:
`` `
@RestController
@RequestMapping (" / mail ")
public class MailController {
@Autowired
Private a MailService MailService;

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

}
`
Can be seen on the interface of a transmission. Very simple, the parameters passed over the recipient's mailbox just fine.

# Test
so far, demo our mail service has been set up better. Our next test test. We start the project. Then tune Interface
http://localhost:9090/zlflovemm/mail/[email protected]

file

Tip has been sent successfully again, and we look forward mail we send case. I can see sending a success. So that we build successful e-mail service.

file

So now it seems, springboot integrated mail service is very simple to configure the mail server, you can use it directly.

send attachments

Sometimes just send us an email content, but also send attachments, then how to achieve it. In fact, very simple. Those configuration is unchanged. We 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("邮件已经发送");
        } catch (MessagingException e) {
            log.error("{}",e);
        }
    }

And when we can see the beginning of the test, there is a little different. Here first

MimeMessage message=mailSender.createMimeMessage();

MimeMessage more powerful than SimpleMailMessage function, can send attachments, the content may be converted into html format transmitted. So when the actual use of general use MimeMessage.
Further send attachments, but also by means of MimeMessageHelper. MimeMessageHelper is to assist the MimeMessage.

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

These and front are the same, the sender recipient, subject, content.
helper.addAttachment () is to add an attachment.

Well, we took the test. You can see the messages you send are attachments. It proved no problem.

file

Extra

Well, so much for you, today's code is also synchronized to the project on github friends.
github address: https: //github.com/QuellanAn/zlflovemm

Come follow ♡

Welcome to the personal public concern number "Programmers love yogurt"

Share a variety of learning materials including java, linux, big data. Information includes video documentation and source code, while sharing themselves and delivery of high-quality technology blog.

If you like attention and remember to share yo ❤
file

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin www.cnblogs.com/quellanan/p/11655972.html