springboot发送邮件实例
时间: 2023-09-10 14:11:31 浏览: 101
springboot发送邮件完整demo
好的,很高兴为您提供帮助。以下是Spring Boot发送邮件的示例代码:
1.添加Maven依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2.application.properties文件配置
```
spring.mail.host=smtp.163.com
spring.mail.username=your_email_address
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
```
3.编写java代码
```
package com.example.maildemo;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
@Component
public class EmailService {
@Autowired
private JavaMailSender emailSender;
public void sendSimpleMessage(
String to, String subject, String text) {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
emailSender.send(message);
}
}
```
在调用sendSimpleMessage方法时传入收件人地址、邮件主题和内容即可发送邮件。
希望能对您有所帮助!
阅读全文