Spring 邮箱:无法自动连接,未找到“JavaMailSender”类型的Bean

toe95027  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(1146)

对于变量“mailSender”,我收到错误消息“无法自动连接。未找到”JavaMailSender“类型的Bean”
电子邮件服务:

private final JavaMailSender mailSender;

public EmailService(JavaMailSender mailSender) {

    this.mailSender = mailSender;
}

application.properties:

spring.mail.host=smtp.xxx.com
spring.mail.port=587
spring.mail.username=xxxx
spring.mail.password=xxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.debug=true
r3i60tvu

r3i60tvu1#

您并不是要在mailsender上创建bean,这里有几个简单的步骤来完成邮件设置。
1.在pom.xml中包含依赖项

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

1.按照您发布的内容设置spring.mail属性
1.在要使用的文件中自动连接邮件发件人

@Autowired
private JavaMailSender emailSender;

1.利用邮件发送者,下面是一个小例子,说明如何做到这一点

MimeMessage mimeMessage = emailSender.createMimeMessage();
mimeMessage.setSubject(subject,"UTF-8");
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true ,"utf-8");
String htmlMsg = emailContent;
helper.setText(emailContent, true); 
helper.setTo(to);
helper.setFrom("noreply@YYYY.com");
emailSender.send(mimeMessage);

相关问题