项目中需要发送邮件,由于是使用springboot开发的,那么需要使用springboot整合邮件,我简要的整理了几个步骤,如下:
第一步:使用maven在pom.xml中添加邮件需要的包
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-mail/<artifactid>
第二步:在application.properties中添加邮件配置
#邮箱发送方协议
spring.mail.host=smtp.1000phone.com
#发送方邮箱
#发送方密码(有些邮箱有授权码,例如QQ邮箱,那么此处不再使用密码,而需要使用授权码)
spring.mail.password=test
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
第三步:发送需要的代码如下
@Component
public class MailService {
@Resource
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to, String subject, String content){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
javaMailSender.send(simpleMailMessage);
}
}
第四步:测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo21ApplicationTests {
@Resource
private MailService mailService;
@Test
public void contextLoads() {
mailService.sendMail("[email protected]", "测试", "测试内容");
}
}
好了,用你自己的邮箱去测试一下吧。
閱讀更多 瘋狂的亮亮 的文章
關鍵字: 邮箱 发送 springboot