SpringBoot中发送Email(基于QQ邮箱版的)
环境:JDK1.8、MAVEN 3.6.1 、eclipse
1.添加email发送的依赖
当前的
pom文件的内容:
UTF-8 org.springframework.boot spring-boot-starter-parent 1.5.22.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-mail junit junit test org.springframework.boot spring-boot-maven-plugin 1.8 1.8
2.查看文档
发现官网上有这样一句话:
Spring Framework提供了一个使用 JavaMailSender界面发送电子邮件的简单抽象 ,Spring Boot为它提供了自动配置以及启动器模块。
所以:可以使用JavaMailSender发送邮箱查看配置
Email (MailProperties)email邮箱的配置
spring.mail.default-encoding=UTF-8# Default MimeMessage encoding.spring.mail.host=# SMTP server host. For instance smtp.example.comspring.mail.jndi-name=# Session JNDI name. When set, takes - precedence to others Session settings.spring.mail.password=# Login password of the SMTP server.spring.mail.port=# SMTP server port.spring.mail.properties.*=# Additional JavaMail Session properties.spring.mail.protocol=smtp# Protocol used by the SMTP server.spring.mail.test-connection=false# Test that the mail server is available on startup.spring.mail.username=# Login user of the SMTP server.
3.配置QQ邮箱的信息
当前application.properties中的内容为:
spring.mail.host=smtp.qq.com
spring.mail.username= xxx@qq.com
spring.mail.password=//your password
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
4.编写工具类
当前的
EmailMessageUtils内容如下
/*** @description 发送邮件的工具类* @author hy* @date 2019-08-13*/
public class EmailMessageUtils {/*** @description 创建简单的邮件对象* @param context 邮件的内容* @param sendTo 邮件的接收者* @param sendFrom 发送邮件的人的邮箱* @return 简单的邮件实例*/public static SimpleMailMessage write(String context, String sendTo, String sendFrom,String title) {SimpleMailMessage simpleMessage = new SimpleMailMessage();simpleMessage.setTo(sendTo);//邮件的接收者simpleMessage.setFrom(sendFrom);//发送邮件的人的邮箱simpleMessage.setText(context);//设置内容simpleMessage.setSubject(title);//设置标题return simpleMessage;}
}
5.编写入口类
当前的
Application类中的内容:
/*** @description 使用SpringBoot发送Email* @author hy* @date 2019-08-13*/
@RestController
@SpringBootApplication
public class Application {@AutowiredJavaMailSender mailSender;@RequestMapping("/sendEmail")public String sendEmail(String sendFrom, String context, String sendTo, String title) {SimpleMailMessage mailMessage = EmailMessageUtils.write(context, sendTo, sendFrom, title);// 通过查询源码获得当前的send可以使用SimpleMailMessage发送一个简单的邮件mailSender.send(mailMessage);return "【发送邮箱成功!】";}public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
6.测试
结果:成功,但是需要使用自己的账号和密码,并且开启那个许可才能使用。网上有就不发了!
7.总结
1.当前发送邮箱的时候需要开启一定的东西,并且需要自己的用户名和密码,还有对应的邮箱的端口
2.发送邮箱可以使用JavaMailSender来发送邮箱,发送的邮件可以使用SimpleMailMessage来创建
以上纯属个人见解,如有问题请联系本人!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
