SpringBoot 发送邮件

使用Spring Boot 开发邮件发送功能。
DAO使用mybatis-plus
百度首页消息设置By丶小丰
-plus
在 pom.xml 中加入依赖

<!--spring boot mail 集成jar-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

编写controller ,service , mapper

controller

package com.lyf.account.message.controller;

import com.lyf.account.message.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author LinYoufeng
 * @version 1.0.0
 * @description TODO
 */

@Slf4j
@RestController
@RequestMapping("/mail")
@CrossOrigin
public class MailController {

    @Autowired
    private MailService mailService;

    /**
     * 发送纯文本邮件
     *
     * @param toAddr  发送给谁
     * @param title   标题
     * @param content 内容
     */
    @RequestMapping(value = "/sms/text", method = RequestMethod.POST)
    public void sendTextMail(@RequestParam String toAddr, @RequestParam String title, @RequestParam String content) {
        mailService.sendTextMail(toAddr, title, content);
    }

    /**
     * 发送 html 邮件
     *
     * @param toAddr
     * @param title
     * @param content 内容(HTML)
     */
    public void sendHtmlMail(String toAddr, String title, String content) {

    }

    /**
     * 发送待附件的邮件
     *
     * @param toAddr
     * @param title
     * @param content
     * @param filePath 附件地址
     */
    public void sendAttachmentsMail(String toAddr, String title, String content, String filePath) {

    }

    /**
     * 发送文本中有静态资源(图片)的邮件
     *
     * @param toAddr
     * @param title
     * @param content
     * @param rscPath 资源路径
     * @param rscId   资源id (可能有多个图片)
     */
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId) {

    }

}

service 实现类,接口自行编写(O(∩_∩)O)

package com.lyf.account.message.service.impl;

import com.lyf.account.message.entity.MailEntity;
import com.lyf.account.message.mapper.MailMapper;
import com.lyf.account.message.service.MailService;
import com.lyf.account.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author LinYoufeng
 * @version 1.0.0
 * @description TODO 发送邮件服务
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MailMapper mailMapper;
    @Autowired
    private BCryptPasswordEncoder encoder;

    // 注入常量
    @Value("${mail.fromMail.addr}")
    private String from;

    @Override
    public void sendTextMail(String toAddr, String title, String content) {
        // 纯文本邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(toAddr);
        message.setSubject(title);
        message.setText(content);
        try {
            mailSender.send(message);
            log.info("Text邮件已经发送。");
            MailEntity mailEntity = new MailEntity();
            mailEntity.setId(idWorker.nextId());
            mailEntity.setTitle(encoder.encode(title));
            mailEntity.setToAddr(encoder.encode(toAddr));
            mailEntity.setContent(encoder.encode(content));
            mailEntity.setFromAddr(encoder.encode(from));
            mailMapper.insert(mailEntity);
        } catch (Exception e) {
            log.error("发送Text邮件时发生异常!", e);
        }

    }

    @Override
    public void sendHtmlMail(String toAddr, String title, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常!", e);
        }

    }

    @Override
    public void sendAttachmentsMail(String toAddr, String title, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            log.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常!", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            log.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
}

Mapper 接口

@Mapper
public interface MailMapper extends SuperMapper<MailEntity> {
}

邮件实体类Entity (集成的AbstractEntity 类字段为ID,createTime,updateTime)

@Data
@TableName("tb_mail")
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class MailEntity extends AbstractEntity implements Serializable {

    private String toAddr;

    private String title;

    private String content;

    private String fromAddr;
}

在配合消息队列进行邮件发送即可!

以下是代码仓库,具体的代码在account_message工程中,配合account_rmq消息队列进行使用
代码仓库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值