Springboot发送邮件
Springboot对发送邮件做了很好的封装,使用起来也非常简单。
首先引入maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
再在appication.properties中进行一些邮件的配置:
spring.mail.host=smtp.163.com
spring.mail.username=你的邮箱名账号
spring.mail.password=你要邮箱授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
接着在业务类中实现发送邮件:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
@Service
public class MailService {
@Resource
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String title, String text, String to) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); // 发送人的邮箱
message.setTo(to); //发给谁对方邮箱
message.setSubject(title); //标题
message.setText(text); //内容
javaMailSender.send(message); //发送
System.out.println("时间: " + LocalDateTime.now() + "邮件发送成功!");
}
}
最后,是测试:
import com.xqnode.mail.service.MailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationTests {
@Resource
private MailService mailService;
@Test
public void contextLoads() {
mailService.sendMail("大猪蹄子", "大猪蹄子", "[email protected]");
}
}
运行这个测试类就可以实现邮件发送。可能会遇到一些问题,例如503错误,这个可能是你的邮箱设置不对,在邮箱里开启smtp服务:
然后获取你的授权码填写在spring.mail.password中:
504错误表示可能你发送的邮件带有敏感的词汇,需要重新编辑一下。