springboot 发送QQ邮件
程序员文章站
2022-03-30 13:42:16
...
1.开启发送端邮箱的smtp服务,登录进入后设置
2.引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.添加设置信息
#配置邮件消息
spring.mail.host=smtp.qq.com
#发送邮件者信箱
spring.mail.username=******@qq.com
#这里不是邮箱的登录密码,而是开启PO3/SMTP服务时邮箱的授权码
spring.mail.password= ******
spring.mail.default-encoding=UTF-8
spring.mail.port=587
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
4.添加邮件工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
@Component
public class MailUtil {
@Autowired
private JavaMailSender jms;
public void sendMail(String toUser, String subject, String text){
try {
MimeMessage mimeMessage = jms.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
// 设置发信人,发信人需要和spring.mail.username配置的一样否则报错
message.setFrom("[email protected]");
// 设置收信人
message.setTo(toUser);
// 设置主题
message.setSubject(subject);
// 第二个参数true表示使用HTML语言来编写邮件
message.setText(text,true);
/*FileSystemResource file = new FileSystemResource(
new File("src/main/resources/static/image/picture.jpg"));
helper.addAttachment("图片.jpg", file);//添加带附件的邮件
helper.addInline("picture",file);//添加带静态资源的邮件*/
jms.send(mimeMessage);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
5.发送时调用工具类
mailUtil.sendMail(接收方, 标题, 内容);
搞定
下一篇: 043进程通信和数据共享