Springboot 设置email发送邮件
Springboot 设置email发送邮件
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置属性(application.properties或者application.yml,此处为yml)
spring:
mail:
host: host地址(可以在你的邮箱设置里找到)
password: 密码
username: 邮箱账号
port: 端口号
test-connection: 是否测试链接
protocol: 类型(默认smtp)
default-encoding: UTF-8
properties:
mail.smtp.socketFactory.fallback : true
mail.smtp.starttls.enable: true
如果没有增加properties:
设置,可能会出现一下530或其他连接报错
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM …
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
@Autowired
private JavaMailSender mailSender; //自动注入的Bean
@Value("${spring.mail.username}")
private String Sender; //读取配置文件中的参数
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(Sender);
message.setTo(Sender); //自己给自己发送邮件
message.setSubject("主题:简单邮件");
message.setText("测试邮件内容");
mailSender.send(message);
}
@Test
public void sendMail() throws Exception {
mailSender.send(new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
/*setRecipient(Message.RecipientType type, Address address),
用于设置邮件的接收者。有两个参数,第一个参数是接收者的类型,第二个参数是接收者。
接收者类型可以是Message.RecipientType.TO,Message.RecipientType.CC和Message.RecipientType.BCC,
TO表示主要接收人,CC表示抄送人,BCC表示秘密抄送人。接收者与发送者一样,通常使用InternetAddress的对象。*/
mimeMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress("目标邮箱的地址"));
mimeMessage.setFrom(new InternetAddress(Sender));
mimeMessage.setText("test");
}
});
}
}