SpringBoot整合JavaMail发一个简单邮件
文章目录
- SpringBoot整合JavaMail发一个简单邮件
- 导入坐标
- 配置
- 写客户端
- SpringBoot整合JavaMail发多部件邮件
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置
spring:
mail:
host: smtp.qq.com
username: 1324@qq.com
password:
写客户端
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
// 发送人
private String from = "****@qq.com";
// 接收人
private String to = "****@163.com";
// 标题
private String subject = "测试邮件";
// 正文
private String content = "测试邮件正文内容";
@Override
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from+"(小甜甜)");
message.setTo(to);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
}
}
SpringBoot整合JavaMail发多部件邮件
其实主要步骤和上面一样,主要是有一些改变
- 不在使用SimpleMailMessage ,而是使用MimeMessage
- 而且不能直接使用message设定属性,要借助MimeMessageHelper
- 发送多部件消息,比如附件,照片等信息,要指定MimeMessageHelper的multipart为true
MimeMessageHelper helper = new MimeMessageHelper(message,true);
- 要发送超链接,要把helper.setText(content,true);的html设定为true
helper.setText(content,true);
其他的配置不变
@Service
public class SendMailServiceImpl2 implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
// 发送人
private String from = "****@qq.com";
// 接收人
private String to = "****@163.com";
// 标题
private String subject = "测试邮件";
// 正文
private String content = "<a href='https://www.baidu.com'>点开有惊喜</a>";
@Override
public void sendMail() {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(from+"(小甜甜)");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
// 添加附件
File f1 = new File("****文件路径");
File f2 = new File("***文件路径");
helper.addAttachment(f1.getName(),f1);
helper.addAttachment("这是文件名.png",f2);
javaMailSender.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}