1 Introduction
In actual projects, the email notification function is often used. For example, users register by email, retrieve their passwords by email, etc.; for example, send system status by email, send report information by email, etc. There are many practical application scenarios. In this article, I will share with you the use of springboot to implement a function of sending emails. (The following function is to use message push)
2. Open POP3 service
What are POP3, SMTP and IMAP?
2.1 Log in to the 163 mailbox on the PC side, click the setting button, and find POP3/SMTP/IMAP, which needs to be turned on, as shown in the figure:
3. Code implementation process
3.1 Introducing dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.2 Configuration file
spring:
mail:
host: smtp.163.com
username: 登录用户名
password: 刚刚自己设置的授权码
default-encoding: utf-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
3.3 Implementation class code
package com.style.service.impl;
import com.style.model.dto.MailDTO;
import com.style.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* @author xufan1
* 邮箱发送实现类
*/
@Service
@Component
public class MailServiceImpl implements MailService {
@Autowired
private MailSender mailSender;
@Override
public void send(MailDTO mailDTO) {
// new 一个简单邮件消息对象
SimpleMailMessage message = new SimpleMailMessage();
// 和配置文件中的的username相同,相当于发送方
message.setFrom("你自己的@163.com");
// 收件人邮箱
message.setTo(mailDTO.getMail());
// 标题
message.setSubject(mailDTO.getTitle());
// 正文
message.setText(mailDTO.getContent());
// 发送
mailSender.send(message);
}
}
3.4 Join DTO
package com.style.model.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
/**
* @author xufan1
* 邮箱发送-前端传输参数
*/
@Data
public class MailDTO implements Serializable {
/**
* 接受邮箱账户
*/
@NotEmpty(message = "邮箱不可为空")
private String mail;
/**
* 邮箱标题
*/
@NotEmpty(message = "邮箱标题不可为空")
private String title;
/**
* 要发送的内容
*/
@NotEmpty(message = "内容不可为空")
private String content;
}
4. Start the service and use postman to call the interface. The
request is successful
4.5 Check whether the partner's email
address is successfully received This blog is sharing a very simple demo, and the project needs to push emails according to specific business needs.