Spring Boot uses Tencent QQ mailbox to send emails

It is relatively simple to send emails in Spring Boot, and it has become a fool. It takes two minutes to read it, three minutes to complete it, and five minutes to make this function is enough.
If you haven't done it in five minutes, please check whether your computer has development tools, whether the computer is too old, and whether the network is slow.


Get the authorization code first : How to obtain the authorization code of Tencent QQ personal mailbox:
insert image description here
insert image description here

Configure the following information in the configuration file in application-local.yml

#在.yml文件中配置一下信息

server:
  port: 8080
  servlet:
    context-path: /mailsender
# 数据源相关配置
spring:
  mail:
    #host: smtp.exmail.qq.com  # 腾讯企业邮箱
    host: smtp.qq.com  # 腾讯个人邮箱
    protocol: smtp
    port: 465
    username: ******@qq.com #邮箱地址
    password: xxxxxxxx  #邮箱授权码
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true
            socketFactory:
              class: com.sun.mail.util.MailSSLSocketFactory
              fallback: false

Add mail sending dependency in pom.xml

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    JavaMailSender jms;

    @Autowired
    MailConfig mailConfig;

    @PostMapping(value = "/send")
    public JsonResult<String> postMail(@RequestBody MailDto mailDto) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(mailConfig.getUserEmail());
            message.setTo(mailDto.getTo()); //收件人邮箱地址
            message.setSubject(mailDto.getSubject());
            message.setText(mailDto.getText());
            jms.send(message);
        } catch (Exception e) {
            throw new MessageException(e.getMessage());
        }
        return JsonResult.success("success");
    }
    
}

After completing the above steps, you can send packets for testing. Tools such as Postman can be used to send test requests to the interface. as follows:

POST :
http://localhost:8080/mailsender/mail/send
{
	"to":"[email protected]",
	"subject": "好久不见",
	"text":"好久不见了,你还好么?顺便问一下,想我了么"
}

Guess you like

Origin blog.csdn.net/forgetmiss/article/details/104600829