【Java】使用Spring Boot+RabbitMQ实现邮件发送功能

使用技术及框架:Spring Boot + RabbitMQ


  1. pom.xml

    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.3.1



    org.springframework.boot
    spring-boot-starter-amqp



    org.springframework.boot
    spring-boot-starter-mail



    org.springframework
    spring-context-support
    4.3.7.RELEASE

  1. application.yml
spring:
  mail:
    host: smtp.qq.com
    port: 25
    username: [email protected]
    password: xxxx # 邮箱授权密码
    personal: xxx  # 发件人别名
    protocol: smtp
    default-encoding: UTF-8
  rabbitmq:
     host: 你的rabbit服务器地址
     port: 5672
     username: username
     password: password
     virtual-host: /
     connection-timeout: 60000

3.邮件发送核心类

@Component
public class MailBase {
    @Autowired
    JavaMailSender javaMailSender;

    /**
     * TODO: 发送邮件
     * @param from      发件人
     * @param personal  发件人昵称
     * @param to        收件人
     * @param subject   主题
     * @param content   内容
     * @param fileUrl   附件
     * @param fileName  附件名称
     */
    public void sendSimpleMail(String from,String personal,String to,String subject,String content,String fileUrl,String fileName){
        MimeMessage message = null;
        try {
            message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from,personal);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (!fileUrl.equals("") && !fileName.equals("")){
                FileSystemResource fileSystemResource=new FileSystemResource(new File(fileUrl));
                helper.addAttachment(fileName,fileSystemResource);
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
  1. rabbit消息队列消息推送端
/**
  *  这里有两种方案,一种是按我下面给出的代码直接CP就可以,另一种是
  *  @Component
  *  public class XXXSender(名字可以自行定义){}
  */
@Component("mailSenders")
public class MailSender {
    private final Logger logger = LoggerFactory.getLogger(MailSender.class);
    @Autowired
    AmqpTemplate amqpTemplate;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.personal}")
    private String personal;
    /**
     * TODO: 将邮件信息内容推送至消息队列
     * @param to        收件人
     * @param subject   主题
     * @param content   内容
     * @param fileUrl   附件
     * @param fileName  附件名称
     * @return
     */
    public String send(String to,String subject,String content,String fileUrl,String fileName){
        logger.info("邮件发送时间:"+new Date())
        //TODO: 封装邮件消息
        BasePage mail = new BasePage();
        mail.put("from",from);
        mail.put("personal",personal);
        mail.put("to",to);
        mail.put("subject",subject);
        mail.put("content",content);
        mail.put("fileUrl",fileUrl);
        mail.put("fileName",fileName);

        amqpTemplate.convertAndSend("mailSev",mail);
        return "已成功推送至邮件服务队列";
    }
}
  1. rabbit消息队列消息接收处理端
@Component
@RabbitListener(queues = "mailSev")
public class MailReceiver {
    private final Logger logger = LoggerFactory.getLogger(MailSender.class);
    @Resource
    MailBase mailBase;

    @RabbitHandler
    public void process(BasePage mail) {
        // TODO 开始处理队列中的内容·推送至邮件服务器进行发送
        mailBase.sendSimpleMail(mail.getString("from"),mail.getString("personal"),
                                     mail.getString("to"),mail.getString("subject"),
                                     mail.getString("content"),mail.getString("fileUrl"),mail.getString("fileName"));
        logger.info("邮件推送时间:" + new Date());
    }
}
  1. BasePage Map的封装类,如果感觉麻烦可以将4/5中BasePage对象替换为Map对象
public class BasePage extends HashMap implements Map{

    private static final long serialVersionUID = 1L;

    Map map = null;
    HttpServletRequest request;
    @SuppressWarnings("unchecked")
    public BasePage(HttpServletRequest request){
        this.request = request;
        Map properties = request.getParameterMap();
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i iteratorSet = this.keySet().iterator();
        while (iteratorSet.hasNext()){
            String key = iteratorSet.next();
            sb.append(key).append("=")
                    .append(this.get(key)).append("&");
        }
        if (sb.length() > 0) sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
}
  1. 调用
@Autowired
MailSender mailSenders;

mailSenders.send("[email protected]","测试邮件","

测试邮件内容

","D:\\test.pdf","测试.pdf");

你可能感兴趣的:(【Java】使用Spring Boot+RabbitMQ实现邮件发送功能)