欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

程序员文章站 2022-07-11 17:02:28
我们都买过火车票,买完后会有邮件提醒,有时候邮件并不是买完票立马就能收到邮件通知,这个就用到了异步邮件发送。这篇文章介绍了怎么实现异步邮件发送 ......

现在邮件发送功能已经是几乎每个系统或网址必备的功能了,从用户注册的确认到找回密码再到消息提醒,这些功能普遍的会用到邮件发送功能。我们都买过火车票,买完后会有邮件提醒,有时候邮件并不是买完票立马就能收到邮件通知,这个就用到了异步邮件发送。

那怎么实现邮件的异步发送呢?

很显然,引入mq是一个不错的选择。刚好这段时间在练习activemq,那就拿activemq来实现异步发送邮件吧。

一、springboot整合javamailsender

在发送异步邮件之前,先来简单介绍下邮件发送的基本内容,了解邮件是怎么发送的,然后再在此基础上添加activemq。

要发送邮件就要用到javamail,它是java官方为方便java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包,它支持常见的邮件协议:smtp/pop3/imap/mime等。想要发送邮件只需要调用javamail的api即可。后来,spring对于javamail进行了封装,然后springboot又进一步封装,现在使用起来非常方便。请看代码:

  1. 新建springboot工程:mail-sender
  2. 添加配置文件:application.properties
    ###mail config ###
    spring.mail.host=smtp.qq.com(配置邮件发送协议)
    spring.mail.username=xxxx@qq.com(发件人,具体配成你需要的邮箱)
    spring.mail.password=对于qq邮箱来说,这里不是密码,而是授权码
    spring.mail.default-encoding=utf-8
    
    mail.to=xxxx@qq.com (为了方便,我这里将收件人统一配置成一个,实际业务中肯定按照实际情况发送的)

    至于授权码的获取,需要到qq邮箱里面 设置->账户,然后到图示的地方,开启服务,然后根据提示获取授权码ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

     

  3. 接下来实现发送邮件的代码
    package com.mail.service.impl;
    
    import com.mail.service.mailservice;
    import org.slf4j.logger;
    import org.slf4j.loggerfactory;
    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.stereotype.service;
    import org.springframework.util.stringutils;
    
    import javax.mail.internet.mimemessage;
    import java.io.file;
    
    @service
    public class mailserviceimpl implements mailservice {
    
        private final logger logger = loggerfactory.getlogger(this.getclass());
        @autowired
        private javamailsender mailsender;//注入javamailsender,具体发送工作需要它完成
    
        @value("${spring.mail.username}")//从配置文件中获取发件人邮箱
        public string from;
    
        /**
         * 发送普通文本邮件
         */
        @override
        public void sendsimplemail(string to, string subject, string context){
            simplemailmessage mailmessage = new simplemailmessage();
            mailmessage.setfrom(from);//发件人
            mailmessage.setto(to);//收件人
            mailmessage.setsubject(subject);//邮件主题
            mailmessage.settext(context);//邮件正文
    
            mailsender.send(mailmessage);//发送邮件
            logger.info("邮件发送成功");
        }
    
        /**
         * 发送html邮件
         */
        @override
        public void sendmimemail(string to, string subject, string context){
            mimemessage mailmessage = mailsender.createmimemessage();
            try{//发送非纯文本的邮件都需要用的helper来解析
                mimemessagehelper helper = new mimemessagehelper(mailmessage);
                helper.setfrom(from);
                helper.setto(to);
    //            helper.setbcc("xxxx@qq.com");//抄送人
                helper.setsubject(subject);
                helper.settext(context,true);//这里的第二个参数要为true才会解析html内容
                mailsender.send(mailmessage);
                logger.info("邮件发送成功");
            } catch(exception ex){
                logger.error("邮件发送失败",ex);
            }
        }
    
        /**
         * 发送带附件的邮件
         */
        @override
        public void sendattachmail(string[] to, string subject, string context, string filepath) {
            mimemessage message = mailsender.createmimemessage();
            try{
                mimemessagehelper helper = new mimemessagehelper(message,true);
                helper.setfrom(from);
                helper.setto(to);
                helper.setsubject(subject);
                helper.settext(context);
    
                filesystemresource file = new filesystemresource(new file(filepath));
                helper.addattachment(file.getfilename(),file);//添加附件,需要用到fileststemresource
    
                mailsender.send(message);
                logger.info("带邮件的附件发送成功");
            }catch(exception ex){
                logger.error("带附件的邮件发送失败",ex);
            }
        }
    
        /**
         * 发送正文带图片的邮件
         */
        @override
        public void sendinlinemail(string to, string subject, string context, string filepath, string resid) {
            mimemessage message = mailsender.createmimemessage();
            try{
                mimemessagehelper helper = new mimemessagehelper(message,true);
                helper.setfrom(from);
                helper.setto(to);
                helper.setsubject(subject);
                helper.settext(context,true);
    
                filesystemresource res = new filesystemresource(new file(filepath));
                helper.addinline(resid, res);
                mailsender.send(message);
                logger.info("邮件发送成功");
            } catch (exception ex){
                logger.error("邮件发送失败",ex);
            }
        }
    
    }

    代码中分别对发送普通文本邮件、html邮件、代码附件的邮件、带图片的邮件进行了示范

  4. 编写测试类
    package com.mail;
    
    import com.mail.service.mailservice;
    import org.junit.test;
    import org.junit.runner.runwith;
    import org.springframework.beans.factory.annotation.autowired;
    import org.springframework.beans.factory.annotation.value;
    import org.springframework.boot.test.context.springboottest;
    import org.springframework.test.context.junit4.springrunner;
    
    @runwith(springrunner.class)
    @springboottest
    public class mailservicetest {
        @autowired
        mailservice mailservice;
    
        @value("${mail.to}")
        private string mailto;
        
        @test
        public  void testsimplemail(){
            mailservice.sendsimplemail(mailto,"纯文本邮件","你好,这是一封测试邮件");
        }
        @test
        public  void testmimemail(){
            string context = "<html>\n" +
                    "<body>\n" +
                    "你好,<br>" +
                    "这是一封html邮件\n" +
                    "</body>\n" +
                    "</html>";
            mailservice.sendmimemail(mailto,"html邮件",context);
        }
    
        @test
        public void testsendattachmail(){
            string[] to = {mailto,"sam.ji@foxmail.com"};
            mailservice.sendattachmail(to,"带附件的邮件","你好,这是一封带附件的邮件","d:\\1.jpg");
        }
    
        @test
        public void testsendinlinemail(){
            string resid = "1";
            string context = "<html><body>你好,<br>这是一封带静态资源的邮件<br><img src=\'cid:"+resid+"\'></body></html>";
            mailservice.sendinlinemail(mailto,"带静态图片的邮件",context,"d:\\1.jpg",resid);
        }
    
    }

     

  5. 分别执行以上@test方法ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

     

邮件发送的代码基本实现了解了,接下来引入activemq的实现。 

二、springboot整合activemq实现异步邮件发送

springboot整合activemq其实也比较简单,首先配置文件中需要添加activemq的相关配置,然后生产者通过注入jmstemplate发送消息,消费者实现监听消费。

实现功能后,最终代码结构:

ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

controller+activemqservice扮演生产者角色,发送消息给消费者;

listener扮演消费者角色,接收到消息后调用mailservice的接口执行邮件发送。

具体代码如下:

  1. 修改application.properties,添加如下内容
    ###queue name###
    com.sam.mail.queue=com.sam.mail.queue
    
    ###activemq config###
    #mq服务地址
    spring.activemq.broker-url=tcp://localhost:61616
    spring.activemq.pool.enabled=false
    #mq用户名和密码
    spring.activemq.user=admin
    spring.activemq.password=admin
    #处理序列化对象需要用到的配置
    spring.activemq.packages.trusted=true
    spring.activemq.packages.trust-all=true

     

  2. 实现mq发送的service
    package com.mail.service.impl;
    
    import com.alibaba.fastjson.json;
    import com.mail.model.mailbean;
    import com.mail.service.activemqservice;
    import org.slf4j.logger;
    import org.slf4j.loggerfactory;
    import org.springframework.beans.factory.annotation.autowired;
    import org.springframework.beans.factory.annotation.value;
    import org.springframework.jms.core.jmstemplate;
    import org.springframework.stereotype.service;
    
    @service
    public class activemqserviceimpl implements activemqservice {
    
        private logger logger = loggerfactory.getlogger(this.getclass());
        @autowired
        jmstemplate template;
    
        @value("${com.sam.mail.queue}")
        private string queuename;
    
        @override
        public void sendmq(string[] to, string subject, string content) {
    
            this.sendmq(to,subject,content,null);
        }
    
        @override
        public void sendmq(string[] to, string subject, string content, string filepath) {
            this.sendmq(to,subject,content,filepath,null);
        }
    
        @override
        public void sendmq(string[] to, string subject, string content, string filepath, string srcid) {
            mailbean bean = new mailbean();
            bean.setto(to);
            bean.setsubject(subject);
            bean.setcontent(content);
            bean.setfilepath(filepath);
            bean.setsrcid(srcid);
            template.convertandsend(queuename,bean);
            logger.info("邮件已经发送到mq:"+ json.tojsonstring(bean));
        }
    }

     

  3. 实现消息发送的controller
    package com.mail.controller;
    
    import com.mail.service.activemqservice;
    import org.springframework.beans.factory.annotation.value;
    import org.springframework.web.bind.annotation.requestmapping;
    import org.springframework.web.bind.annotation.restcontroller;
    
    import javax.annotation.resource;
    
    /**
     * @author java开发老菜鸟
     */
    
    @restcontroller
    public class mailsendercontroller {
    
        @resource
        activemqservice activemqservice;
    
        @value("${mail.to}")
        private string mailto;
        
        @requestmapping("/sendsimplemail.do")
        public void sendsimplemail(){
            string[] to = {mailto};
            string subject = "普通邮件";
            string context = "你好,这是一封普通邮件";
            activemqservice.sendmq(to, subject, context);
        }
    
        @requestmapping("/sendattachmail.do")
        public void sendattachmail(){
            string[] to = {mailto};
            string subject = "带附件的邮件";
            string context = "<html><body>你好,<br>这是一封带附件的邮件,<br>具体请见附件</body></html>";
            string filepath = "d:\\1.jpg";
            activemqservice.sendmq(to, subject, context, filepath);
        }
    
        @requestmapping("/sendmimemail.do")
        public void sendmimemail(){
            string[] to = {mailto};
            string subject = "普通邮件";
    
            string filepath = "d:\\1.jpg";
            string resid = "1.jpg";
            string context = "<html><body>你好,<br>这是一封带图片的邮件,<br>请见图片<br><img src=\'cid:"+resid+"\'></body></html>";
            activemqservice.sendmq(to, subject, context, filepath, resid);
        }
    
    }

     

  4. mailbean的具体实现
    public class mailbean implements serializable {
        private string from;//发件人
        private string[] to;//收件人列表
        private string subject;//邮件主题
        private string content;//邮件正文
        private string filepath;//文件(图片)路径
        private string srcid;//图片名
    
        ......  
        getter/setter略
        ......  
    }

     

  5. 消费者监听实现
    package com.mail.listener;
    
    import com.mail.model.mailbean;
    import com.mail.service.mailservice;
    import org.slf4j.logger;
    import org.slf4j.loggerfactory;
    import org.springframework.beans.factory.annotation.autowired;
    import org.springframework.jms.annotation.jmslistener;
    import org.springframework.stereotype.service;
    
    import javax.jms.objectmessage;
    import java.io.serializable;
    
    /**
     * 监听到mq后调用mailservice执行邮件发送操作
     */
    @service
    public class sendmailmqlistener {
    
        logger logger = loggerfactory.getlogger(this.getclass());
    
        @autowired
        mailservice mailservice;
    
        /**
         * 通过监听目标队列实现功能
         */
        @jmslistener(destination = "${com.sam.mail.queue}")
        public void dealsendermailmq(objectmessage message){
            try{
                serializable object = message.getobject();
                mailbean bean =  (mailbean) object;
                mailservice.sendmail(bean.getto(),bean.getsubject(),bean.getcontent(),bean.getfilepath(),bean.getsrcid());
                logger.error("消费者消费邮件信息成功");
            } catch (exception ex){
                logger.error("消费者消费邮件信息失败:"+ ex);
            }
    
        }
    }

     

  6. 监听器调用的发送接口在前面没有,是新加的
    @override
        public void sendmail(string[] to, string subject, string context, string filepath, string resid ){
            mimemessage message = mailsender.createmimemessage();
            try{
                mimemessagehelper helper = new mimemessagehelper(message, true);
                helper.setfrom(from);
                helper.setto(to);
                helper.setsubject(subject);
                helper.settext(context, true);
                if(!stringutils.isempty(filepath) && !stringutils.isempty(resid)){//文件路径和resid都不为空,视为静态图片
                    filesystemresource resource = new filesystemresource(new file(filepath));
                    helper.addinline(resid, resource);
                } else if(!stringutils.isempty(filepath)){//只有文件路径不为空,视为附件
                    filesystemresource resource = new filesystemresource(new file(filepath));
                    helper.addattachment(resource.getfilename(),resource);
                }
    
                mailsender.send(message);
                logger.info("邮件发送成功");
            } catch (exception ex){
                logger.error("邮件发送错误:", ex);
            }

     

  7. 启动工程,分别调用controller中的uri,查看结果ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

    ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

    ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

    ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

     

  8. 查看下mq的页面控制台ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送

     

 至此,功能已经实现。

三、遇到过的问题

在实现这个demo的时候,遇到了一些问题,也把它们列出来,给别人一个参考

第一个问题:

消费者消费邮件信息失败:javax.jms.jmsexception: failed to build body from content. serializable class not available to broker. reason: java.lang.classnotfoundexception: forbidden class com.mail.model.mailbean! this class is not trusted to be serialized as objectmessage payload. please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.

this class is not trusted to be serialized as objectmessage payload,是说我的mailbean对象不是可以新人的序列化对象,

原因:

传递对象消息时 ,activemq的objectmessage依赖于java的序列化和反序列化,但是这个过程被认为是不安全的。具体信息查看报错后面的那个网址:

http://activemq.apache.org/objectmessage.html

解决方法:

在application.properties文件中追加下面的配置即可

spring.activemq.packages.trust-all=true

 

第二个问题:

***************************
application failed to start
***************************

description:

a component required a bean of type 'com.mail.service.activemqservice' that could not be found.


action:

consider defining a bean of type 'com.mail.service.activemqservice' in your configuration.

原因:

activemqservice没有被spring扫描并初始化,然后我在代码用通过@autowaired注解使用获取不到。 找了之后发现是我的@service注解放到了interface上,应该放到service的impl类上。

解决方法:

将@service注解放到impl类上

 

 好,以上就是springboot+activemq+javamail实现异步邮件发送的全部内容了,

觉得有帮助的话,记得点赞哦~~