SpringBoot发送邮件的方法
2022/3/20 6:27:59
本文主要是介绍SpringBoot发送邮件的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. 导入相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.6.3</version> </dependency>
2. 打开邮箱设置
3. 编写配置文件
spring.mail.host=smtp.qq.com spring.mail.username=用户名 spring.mail.password=这里填邮箱的授权码,不是密码! spring.mail.protocol=smtps spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
4. 完成发送邮件功能
@Component public class MailClient { //java提供的发送邮件的接口 @Autowired private JavaMailSender mailSender; //将配置文件中邮件发送方的邮箱地址配置到类中 @Value("${spring.mail.username}") private String from; /** * * @param to 接收方 * @param subject 标题 * @param content 内容 */ public void sendMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); try { helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true);//设置为true: 开启发送html页面功能 mailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { e.printStackTrace(); } } }
5. 测试
public class MailUtilTest { @Autowired private MailUtil mailUtil; //模板引擎,用来解析thymeleafs下的html文件 @Autowired private TemplateEngine templateEngine; /* 简单的测试,只是发送一些文本内容:“发送成功” */ @Test public void test1() { mailUtil.sendMail("xxxxxx@163.com", "TEST", "发送成功!"); } /* 常用:发送html页面 */ @Test public void test2() { Context context = new Context(); //设置html中参数 context.setVariable("username", "吴京"); //将html和context封装成一个字符串 String content = templateEngine.process("/mail/demo", context); //发送邮件 mailUtil.sendMail("xxxxxxx@163.com", "TEST", content); } }
这篇关于SpringBoot发送邮件的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?
- 2024-05-30java excel上传--poi
- 2024-05-30安装笔记本应用商店的pycharm,再安排pandas等模块,说是没有打包工具?
- 2024-05-29java11新特性