maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml配置
mail:
host: smtp.163.com # 发件服务器地址,不同邮件平台地址不同
port: 25 #常用邮件端口25、109、110、143、465、995、993、994 如果开启了SSL安全则使用对应的端口号,25为非加密端口号
username: xxx@163.com #发送邮件的账号
password: xxxx#发送邮件账号的授权码,这里的授权码不是验证码.需要到邮箱
default-encoding: utf-8 #设置编码
properties: # 设置邮件超时时间防止服务器阻塞
timeout: 5000
connection-timeout: 5000
write-timeout: 5000
核心代码
package com.example.rabbitmq_demo.email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
/**
* @author: Zeke
* @create: 2023-07-19 10:11
**/
@Service
@Slf4j
public class Mail163impl implements Mail{
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
String sendUserName;
String[] emails = { "你要发送的邮箱1","你要发送的邮箱2" }; //多发
spring email="你要发送的邮箱1"; //单发
public Boolean sendEMail(String Subject) {
try {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(sendUserName); //设置发送邮件账号
simpleMailMessage.setTo(emails); //设置接收邮件的人,可以多个
simpleMailMessage.setSubject("eMailCmd"); //设置发送邮件的主题
simpleMailMessage.setText(Subject); //设置发送邮件的内容
mailSender.send(simpleMailMessage);
return true;
} catch (MailException e) {
log.error("邮件发送失败!");
return false;
}
}
}
测试
@Autowired
Mail mail;
@Test
void contextLoads() {
Boolean aBoolean = mail.sendEMail("521");
System.out.println(aBoolean);
}