springboot发送邮件
时间: 2023-07-08 13:51:42 浏览: 108
Springboot发送邮件
好的,下面是使用 Spring Boot 发送邮件的步骤:
1. 在 `pom.xml` 文件中添加 Spring Boot 发送邮件所需的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2. 在 `application.yml` 文件中配置邮件服务器信息,例如:
```
spring:
mail:
host: smtp.qq.com
username: your_email@qq.com
password: your_password
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
mail.smtp.ssl.trust: smtp.qq.com
default-encoding: UTF-8
```
3. 创建一个邮件服务类,例如:
```
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
/**
* 发送简单邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param content 邮件内容
* @throws MessagingException
*/
public void sendSimpleMail(String to, String subject, String content) throws MessagingException {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your_email@qq.com");
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
/**
* 发送 HTML 邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param content 邮件内容
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your_email@qq.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
}
```
4. 在需要发送邮件的地方调用邮件服务类的方法即可。
示例代码:
```
@RestController
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/sendSimpleMail")
public String sendSimpleMail() throws MessagingException {
mailService.sendSimpleMail("recipient_email@qq.com", "测试邮件", "这是一封测试邮件");
return "发送成功";
}
@GetMapping("/sendHtmlMail")
public String sendHtmlMail() throws MessagingException {
String content = "<html><body><h1>这是一封测试邮件</h1></body></html>";
mailService.sendHtmlMail("recipient_email@qq.com", "测试邮件", content);
return "发送成功";
}
}
```
以上就是使用 Spring Boot 发送邮件的步骤,希望能对你有所帮助。
阅读全文