java中的接口是类吗
276
2022-08-27
Spring Boot整合邮箱发送邮件实例
目录1.准备工作2.代码整合总结
1. 准备工作
登录进自己的 qq 邮箱获取授权码
设置 – 账户 – POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
点击开始获取授权码,将授权码保存下来,下面代码整合的时候需要使用
2. 代码整合
创建一个 Spring Boot 项目,引入以下依赖
配置文件
server:
port: 8080
spring:
# email 配置
mail:
# SMTP 服务器地址
host: smtp.qq.com
username: # 你的qq 邮箱地址
password: # 授权码,上面从 qq 邮箱官网得到的授权码
port: 587
protocol: smtp
default-encoding: UTF-8
创建一个邮件收件人信息的实体类
/**
* @author lishisen
* @description 邮件收件人信息
* @date 2022/1/9 9:37
**/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmailModel implements Serializable {
// 收件人邮箱地址
private String receiveEmailAddress;
// 邮箱主题
private String emailTheme;
// 邮件内容
private String emailContent;
}
创建一个服务提供类,SendEmailService.java
/**
* @author lishisen
* @description 邮件发送服务类
* @date 2022/1/9 9:40
**/
@Slf4j
@Component
public class SendEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private JavaMailSenderImpl javaMailSenderImpl;
// 发送者地址
private String posterAddress = "1876419736@qq.com";
// 发送者名称
private String posterName = "测试邮件发送";
/**
* 文本发送
**/
public void sendEmailAsText(final EmailModel emailModel) {
System.out.println(emailModel.toString());
MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
mimeMessage.setFrom(posterAddress);
mimeMessage.setRecipients(Message.RecipientType.TO, emailModel.getReceiveEmailAddress());
mimeMessage.setText("发送者地址:" + posterAddress + '\n'
+ "发送者名称:" + posterName + '\n'
+ "内容:" + emailModel.getEmailContent());
};
try {
this.javaMailSender.send(mimeMessagePreparator);
log.info("邮箱已返送至[{}]邮箱!", emailModel.getReceiveEmailAddress());
} catch (MailException e) {
log.error("邮箱异常:{}", e);
}
}
/**
* html 网页发送
* 该方法为同步方法
**/
public void sendEmailAsSysExceptionHtml(final EmailModel emailModel, String info) {
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
try {
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(posterAddress);
mimeMessageHelper.setTo(emailModel.getReceiveEmailAddress());
mimeMessageHelper.setSubject(emailModel.getEmailTheme());
mimeMessageHelper.setText(
" \n" +
"\n" +
"
" \n" +
"
"\n" +
"&http://lt;body>\n" +
"
"
emailModel.getEmailContent() +
"
"\n" +
"
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~