流程
- 以网易邮箱为例,先注册一个163邮箱,并且获取
POP3/SMTP服务
授权码 - 通过这个授权码操作该邮箱往其他邮箱里发送邮件。
核心代码
package net.xdclass.component;
public interface MailService {
void sendMail(String to,String subject, String content);
}
package net.xdclass.component.impl;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.component.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.from}")
private String from;
@Override
public void sendMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
log.info("邮件发送成功:{}",message.toString());
}
}
spring:
mail:
host: smtp.163.com
username: 17862806857@163.com
password: QSWBRCQMQNFBURLC
from: 17862806857@163.com
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>