获取邮箱授权码
打开POP3/SMTP服务
复制授权码
pom.xml导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
修改application.yml
spring:
mail:
host: smtp.163.com
username: 邮箱名
password: 授权码
port: 465
protocol: smtp
default-encoding: UTF-8
properties:
mail:
smtp:
ssl:
enable: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
debug: true
调用JavaMailSender发送邮件
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.Date;
import java.util.List;
@Service
public class MailServiceImpl {
private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl .class);
/**
* 注入邮件工具类
*/
@Autowired(required = false)
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String sendMailer; // 发送者邮箱
/**
* receivers: 接收者邮箱
*/
@Override
public void sendTextMailMessage(List<String> receivers, String subject, String content) {
try {
logger.info("发送:{} -> {}", sendMailer, receivers);
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
mimeMessageHelper.setFrom(sendMailer);
mimeMessageHelper.setTo(receivers.toArray(String[]::new));
//邮件主题
mimeMessageHelper.setSubject(subject);
//邮件内容
mimeMessageHelper.setText(content);
//邮件发送时间
mimeMessageHelper.setSentDate(new Date());
//发送邮件
javaMailSender.send(mimeMessageHelper.getMimeMessage());
logger.info("发送邮件成功:{} -> {}", sendMailer, receivers);
} catch (Exception e) {
logger.error("发送邮件失败:{} -> {}", sendMailer, receivers);
logger.error("发送邮件失败", e);
throw new BusinessException(LarkPassRestResultCode.ERROR, "发送邮件失败");
}
}
}