springboot发送邮件 outlook
时间: 2023-11-30 08:43:26 浏览: 191
springboot发送邮件
以下是使用SpringBoot发送邮件的示例代码,其中包括了如何发送带附件的邮件和如何开启TLS验证:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootApplication
@EnableConfigurationProperties(MailProperties.class)
public class MailApplication {
@Autowired
private JavaMailSender mailSender;
@Autowired
private MailProperties mailProperties;
public static void main(String[] args) {
SpringApplication.run(MailApplication.class, args);
}
public void sendMailWithAttachment() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(mailProperties.getUsername());
helper.setTo("recipient@example.com");
helper.setSubject("Test email with attachment");
// 添加附件
FileSystemResource file = new FileSystemResource(new File("attachment.txt"));
helper.addAttachment("attachment.txt", file);
// 发送邮件
mailSender.send(message);
}
}
```
在application.properties文件中添加以下配置:
```
spring.mail.username=xxxxxxx@outlook.com
spring.mail.password=xxxxxxxxx
spring.mail.port=587
spring.mail.host=smtp-mail.outlook.com
spring.mail.properties.mail.smtp.starttls.required=true
```
注意:在使用Outlook发送邮件时,需要开启TLS验证,否则会显示匿名用户无法通过验证。
阅读全文