springboot发送html邮件
时间: 2023-04-30 07:01:52 浏览: 133
Springboot发送邮件
Spring Boot可以通过JavaMailSender发送HTML邮件。以下是发送HTML邮件的步骤:
1. 在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2. 在application.properties文件中添加SMTP服务器的配置信息:
```
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
3. 创建一个邮件服务类,该类使用JavaMailSender发送HTML邮件:
```
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendHtmlEmail(String to, String subject, String htmlBody) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlBody, true);
javaMailSender.send(message);
}
}
```
4. 在需要发送HTML邮件的地方调用邮件服务类的sendHtmlEmail方法:
```
@Autowired
private EmailService emailService;
public void sendEmail() throws MessagingException {
String to = "recipient-email@example.com";
String subject = "Test HTML Email";
String htmlBody = "<h1>Hello World!</h1><p>This is a test HTML email.</p>";
emailService.sendHtmlEmail(to, subject, htmlBody);
}
```
以上就是使用Spring Boot发送HTML邮件的步骤。
阅读全文