SpringBoot整合mail发送邮件信息

前因

温馨提醒:阅读本文需要6分钟

上一个博客中我们介绍过了怎么通过阿里云的短信服务发送短信,这次半藏商城中的用户付款成功,定时发送邮件提醒及时付款,以及修改密码都用到了发送邮件功能,这就涉及到mail方面的应用了,我们这次使用的是springboot集合的mail,接下来分享一下我的发送邮件信息的实现流程。

Maven引包

首先进行在pom.xml中进行引包,还在为引哪个版本的包而困扰的同学推荐这个Maven在线查找依赖的网站,想用什么输入搜索,复制过来就可以了。

<!-- springboot集成发送邮件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

配置application.properties

#springboot集成发送邮件
##邮箱服务器地址QQ smtp.qq.com sina smtp.sina.cn aliyun smtp.aliyun.com 163 smtp.163.com
spring.mail.host=smtp.qq.com
spring.mail.username=hanzo-mall@foxmail.com
#QQ邮箱应该使用授权码
spring.mail.password=ksdisswiuxbhddib
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
#使用SMTPS协议465端口
# ssl 配置
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
##发送邮件地址
mail.fromMail.sender=hanzo-mall@foxmail.com

我简单介绍一下配置的意思,spring.mail.host是你使用的邮箱的服务,username是邮箱的地址,password注意并不是邮箱的密码,而是邮箱的授权码(不了解的可以百度,有详细的教程怎么获取授权码)。(大坑注意->)在本地默认不配置发送邮件的协议端口号时,默认是使用25这个端口发送的,在本地是可以使用的,但是阿里云服务器默认是禁用这个端口的,原因是为了防止垃圾短信。所以我们这里需要ssl配置使用SMTPS协议465端口才可以在服务器上正常发送短信。

编写业务层接口代码

/**
 * @author 皓宇QAQ
 * @email 2469653218@qq.com
 * @link https://github.com/Tianhaoy
 * 2020年3月16日 17:50:24
 * @发送邮箱接口
 */
public interface MailSendService {
    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 发送HTML邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendHtmlMail(String to, String subject, String content);

    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath);
}

编写业务层实现类

/**
 * @author 皓宇QAQ
 * @email 2469653218@qq.com
 * @link https://github.com/Tianhaoy/hanzomall
 * 2020年3月16日 17:50:24
 * @发送邮箱接口实现类
 */
@Slf4j
@Service
public class MailSendServiceImpl implements MailSendService {

    //Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
    @Autowired
    private JavaMailSender mailSender;

    // 配置文件中的发送者
    @Value("${mail.fromMail.sender}")
    private String sender;

    /**
     * 简单文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(sender);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        try {
            mailSender.send(message);
            log.info("邮件接收人"+to+"主题"+subject+"内容"+content+"邮件发送成功");
        }catch (Exception e){
            log.error("邮件接收人"+to+"主题"+subject+"内容"+content+"邮件发送出现异常");
            log.error("异常信息为"+e.getMessage());
            log.error("异常堆栈信息为-->");
            e.printStackTrace();

        }
    }

    /**
     * html邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(sender);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容,html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }

    /**
     * 带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }
}

编写发送邮件验证码Controller类

/**
 * @author 皓宇QAQ
 * @email 2469653218@qq.com
 * @link https://github.com/Tianhaoy/hanzomall
 * @发送邮箱
 */
@Slf4j
@RestController
public class MailSendController {

    @Resource
    private MailSendService mailSendService;

    @RequestMapping("/sendCodeMail")
    public Result mailSendKaptcha(HttpSession httpSession) {
        //生成6位随机码
        try {
            String randomCode = EmailCodeUtils.getRandomCode();
            HanZoMallUserVO user = (HanZoMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
            String emailAddress = user.getEmailAddress();
            mailSendService.sendSimpleMail(emailAddress, "【半藏商城修改密码】", "您好,你本次的验证码为:"+randomCode+"有效期为60秒!");
            httpSession.setAttribute(Constants.RANDOM_CODE,randomCode);//将随机验证码放到session中
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultGenerator.genFailResult("服务怠机,请稍后重试");
        }

        return ResultGenerator.genSuccessResult();
    }

    @RequestMapping("/sendHtmlMail")
    public String SendHtmlMail() {
        String content = "<html><body><h3>hello world ! --->Html邮件</h3></body></html>";
        mailSendService.sendHtmlMail("2469653218@qq.com","test", content);
        return "success";
    }

    @RequestMapping("/sendAttachmentsMail")
    public String sendAttachmentsMail() {
        String filePath = "";//文件的路径
        mailSendService.sendAttachmentsMail("2469653218@qq.com","test","testfile",filePath);
        return "success";
    }
}

小结

到此为止,整个发送邮件信息的流程就介绍完毕了,知识只有分享出来才有价值。如果有问题的话,可以在关于我的页面,通过我的邮箱联系我进行探讨。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值