写在前面:
继续记录自己的SpringBoot学习之旅,这次是SpringBoot应用相关知识学习记录。若看不懂则建议先看前几篇博客,详细代码可在我的Gitee仓库SpringBoot克隆下载学习使用!
@Service
public class SendMailMessageServiceImpl implements sendMailMessageService {
@Autowired
private JavaMailSender javaMailSender;
// 邮件发送方 自己选择邮箱地址
private String sendPerson = "xxxx@qq.com";
// 邮件接收方 自己选择邮箱地址
private String acceptPerson = "xxx@163.com";
// 邮件标题
private String subject = "测试邮件标题";
// 邮件正文
private String context = "邮件正文";
@Override
public void sendMailMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(sendPerson + "(小甜甜)");
simpleMailMessage.setTo(acceptPerson);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(context);
javaMailSender.send(simpleMailMessage);
}
spring:
mail:
host: smtp.qq.com
# 这里使用QQ邮箱来发送
username: xxxxx@qq.com
# QQ邮箱设置-账户-开启SMTP后得到验证码(需用手机发验证码)
password: xxxxxxx
@Service
public class SendMailMessageServiceImpl2 implements sendMailMessageService {
@Autowired
private JavaMailSender javaMailSender;
// 邮件发送方
private String sendPerson = "xxxx@qq.com";
// 邮件接收方
private String acceptPerson = "xxxx@163.com";
// 邮件标题
private String subject = "测试邮件标题";
// 邮件正文
private String context = "点开有惊喜";
@Override
public void sendMailMessage() {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(sendPerson + "(小甜甜)");
messageHelper.setTo(acceptPerson);
messageHelper.setSubject(subject);
messageHelper.setText(context,true);
// 添加附件
File file = new File("D:\\Javaprogram\\javaLittlePractition\\SpringBoot\\server.log");
messageHelper.addAttachment(file.getName(),file);
javaMailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}