pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
腾讯企业邮箱配置,
端口465,配置SSL
application.properties
spring.mail.host=smtp.exmail.qq.com
spring.mail.port=465
spring.mail.username=xxxx@xxx.com #发送者邮件
spring.mail.password=xxxx #密码,不能是管理员添加的初始密码,不然会报501错误(需要改过密码)
spring.mail.toadmin=user1@qq.com;user2@qq.com #用;分开
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enabled=true
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
增加一个发送邮件的service接口
public interface MailService {
public void sendMail(String from, String[] to, String title,String content);
}
接口实现
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;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Date;
@Service
@Transactional
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.toadmin}")
private String toTmp;
@Override
public void sendMailByRemind(String tel) {
String[] to = toTmp.split(";"); //目标必须字符串或数组,多接收人时必须为数组,用字府串会报异常
sendMail(from, to, "新用户注册提醒", new Date()+"注册手机号为:"+tel);
}
@Override
public void sendMail(String from, String[] to, String title, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //腾讯的限制,发送人必须与发送邮箱相同,不同会报异常
message.setTo(to);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
System.out.println("send mail to: "+ Arrays.toString(to) +"and content: "+ content);
}
}
本地测试发送一个邮件要20秒,故而改成用异步发送邮件,
添加异步接口Service
public interface AnsyService {
public void sendMailByRemind(String tel);
}
异步实现
@Service
@Transactional
public class AnsyServiceImpl implements AnsyService{
@Autowired
MailService mailService;
@Async
@Override
public void sendMailByRemind(String tel) {
mailService.sendMailByRemind(tel);
}
}
本文详细介绍如何在Spring Boot项目中集成腾讯企业邮箱服务,包括pom.xml依赖配置、application.properties参数设置及邮件发送Service接口实现。通过示例代码讲解如何同步及异步发送邮件,解决常见错误如501错误。
2050

被折叠的 条评论
为什么被折叠?



