赞
踩
以QQ设置中为例:
第一步,新建项目SpringBoot工程。
第二步,引入maven依赖
发送邮件所需依赖,在pom.xml加入。
<!--mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第三步,配置application.properties配置文件
spring.application.name=mail
spring.mail.host=smtp.qq.com
spring.mail.username=xxx@qq.com
spring.mail.password=your_password # 注意:这里是你的邮箱的第三方客户端密码,而不是邮箱的登录密码!
spring.mail.default-encoding=UTF-8
此处生成密码方法如下,点击邮箱设置,生成密码
service
// 将配置文件的username注入 @Value("${spring.mail.username}") private String from; @Autowired private JavaMailSender javaMailSender; /** * 发送带图片的邮件 * @param Id * @param to * @param subject * @param content * @param id * @throws MessagingException */ public void sendImgResourceMail(String to, String subject, String content, String Id, String id) { logger.info("发送带图片的邮件"); MimeMessage mailMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = null; try { helper = new MimeMessageHelper(mailMessage , true); helper.setTo(to); helper.setSubject(subject); helper.setText(content , true); // 发 送 者 helper.setFrom(from); // 添加图片 FileSystemResource srcPath = new FileSystemResource(new File(Id)); helper.addInline(Id , srcPath); javaMailSender.send(mailMessage); // 发送邮件 } catch (MessagingException e) { logger.info("发送带图片的邮件失败"); } }
测试
@Test
public void sendImgResourceMail() throws MessagingException {
String srcPath = "F:\\img\\1.png";
String Id = "666";
String content = "<html><body><img src='cid:" + Id + "'/></body></html>";
mailService.sendImgResourceMail("xxx@163.com",
"Test",
content,
srcPath,
Id);
}
<!--mail模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
你好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!
<!--/*@thymesVar id="id" type=""*/-->
<a href="#" th:href="@{http://www.xxx.com/register/{id}(id=${id})}">激活账号</a>
</body>
</html>
测试
@Autowired
private TemplateEngine templateEngine;
@Test
public void TestTemplateMail() throws MessagingException {
Context context = new Context();
context.setVariable("id", "999");
String emailContent = templateEngine.process("mailTemplate", context);
mailService.sendHtmlMail("xxx@qq.com","Test",emailContent);
}
成功收到邮件:
Github仓库地址: https://github.com/xmpjava/mail-java
Gitee仓库地址:
https://gitee.com/love-code-bear/mail
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。