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

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

很显然,引入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
    1. ###mail config ###
    2. spring.mail.host=smtp.qq.com(配置邮件发送协议)
    3. spring.mail.username=xxxx@qq.com(发件人,具体配成你需要的邮箱)
    4. spring.mail.password=对于qq邮箱来说,这里不是密码,而是授权码
    5. spring.mail.default-encoding=utf-8
    6. mail.to=xxxx@qq.com (为了方便,我这里将收件人统一配置成一个,实际业务中肯定按照实际情况发送的)

    至于授权码的获取,需要到qq邮箱里面 设置->账户,然后到图示的地方,开启服务,然后根据提示获取授权码

     

  3. 接下来实现发送邮件的代码
    1. package com.mail.service.impl;
    2. import com.mail.service.MailService;
    3. import org.slf4j.Logger;
    4. import org.slf4j.LoggerFactory;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.beans.factory.annotation.Value;
    7. import org.springframework.core.io.FileSystemResource;
    8. import org.springframework.mail.SimpleMailMessage;
    9. import org.springframework.mail.javamail.JavaMailSender;
    10. import org.springframework.mail.javamail.MimeMessageHelper;
    11. import org.springframework.stereotype.Service;
    12. import org.springframework.util.StringUtils;
    13. import javax.mail.internet.MimeMessage;
    14. import java.io.File;
    15. @Service
    16. public class MailServiceImpl implements MailService {
    17. private final Logger logger = LoggerFactory.getLogger(this.getClass());
    18. @Autowired
    19. private JavaMailSender mailSender;//注入JavaMailSender,具体发送工作需要它完成
    20. @Value("${spring.mail.username}")//从配置文件中获取发件人邮箱
    21. public String from;
    22. /**
    23. * 发送普通文本邮件
    24. */
    25. @Override
    26. public void sendSimpleMail(String to, String subject, String context){
    27. SimpleMailMessage mailMessage = new SimpleMailMessage();
    28. mailMessage.setFrom(from);//发件人
    29. mailMessage.setTo(to);//收件人
    30. mailMessage.setSubject(subject);//邮件主题
    31. mailMessage.setText(context);//邮件正文
    32. mailSender.send(mailMessage);//发送邮件
    33. logger.info("邮件发送成功");
    34. }
    35. /**
    36. * 发送HTML邮件
    37. */
    38. @Override
    39. public void sendMimeMail(String to, String subject, String context){
    40. MimeMessage mailMessage = mailSender.createMimeMessage();
    41. try{//发送非纯文本的邮件都需要用的helper来解析
    42. MimeMessageHelper helper = new MimeMessageHelper(mailMessage);
    43. helper.setFrom(from);
    44. helper.setTo(to);
    45. // helper.setBcc("xxxx@qq.com");//抄送人
    46. helper.setSubject(subject);
    47. helper.setText(context,true);//这里的第二个参数要为true才会解析html内容
    48. mailSender.send(mailMessage);
    49. logger.info("邮件发送成功");
    50. } catch(Exception ex){
    51. logger.error("邮件发送失败",ex);
    52. }
    53. }
    54. /**
    55. * 发送带附件的邮件
    56. */
    57. @Override
    58. public void sendAttachMail(String[] to, String subject, String context, String filePath) {
    59. MimeMessage message = mailSender.createMimeMessage();
    60. try{
    61. MimeMessageHelper helper = new MimeMessageHelper(message,true);
    62. helper.setFrom(from);
    63. helper.setTo(to);
    64. helper.setSubject(subject);
    65. helper.setText(context);
    66. FileSystemResource file = new FileSystemResource(new File(filePath));
    67. helper.addAttachment(file.getFilename(),file);//添加附件,需要用到FileStstemResource
    68. mailSender.send(message);
    69. logger.info("带邮件的附件发送成功");
    70. }catch(Exception ex){
    71. logger.error("带附件的邮件发送失败",ex);
    72. }
    73. }
    74. /**
    75. * 发送正文带图片的邮件
    76. */
    77. @Override
    78. public void sendInlineMail(String to, String subject, String context, String filePath, String resId) {
    79. MimeMessage message = mailSender.createMimeMessage();
    80. try{
    81. MimeMessageHelper helper = new MimeMessageHelper(message,true);
    82. helper.setFrom(from);
    83. helper.setTo(to);
    84. helper.setSubject(subject);
    85. helper.setText(context,true);
    86. FileSystemResource res = new FileSystemResource(new File(filePath));
    87. helper.addInline(resId, res);
    88. mailSender.send(message);
    89. logger.info("邮件发送成功");
    90. } catch (Exception ex){
    91. logger.error("邮件发送失败",ex);
    92. }
    93. }
    94. }

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

  4. 编写测试类
    1. package com.mail;
    2. import com.mail.service.MailService;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.beans.factory.annotation.Value;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. @RunWith(SpringRunner.class)
    10. @SpringBootTest
    11. public class MailServiceTest {
    12. @Autowired
    13. MailService mailService;
    14. @Value("${mail.to}")
    15. private String mailTo;
    16. @Test
    17. public void testSimpleMail(){
    18. mailService.sendSimpleMail(mailTo,"纯文本邮件","你好,这是一封测试邮件");
    19. }
    20. @Test
    21. public void testMimeMail(){
    22. String context = "<html>\n" +
    23. "<body>\n" +
    24. "你好,<br>" +
    25. "这是一封HTML邮件\n" +
    26. "</body>\n" +
    27. "</html>";
    28. mailService.sendMimeMail(mailTo,"HTML邮件",context);
    29. }
    30. @Test
    31. public void testSendAttachMail(){
    32. String[] to = {mailTo,"sam.ji@foxmail.com"};
    33. mailService.sendAttachMail(to,"带附件的邮件","你好,这是一封带附件的邮件","D:\\1.jpg");
    34. }
    35. @Test
    36. public void testSendInlineMail(){
    37. String resId = "1";
    38. String context = "<html><body>你好,<br>这是一封带静态资源的邮件<br><img src=\'cid:"+resId+"\'></body></html>";
    39. mailService.sendInlineMail(mailTo,"带静态图片的邮件",context,"D:\\1.jpg",resId);
    40. }
    41. }

     

  5. 分别执行以上@Test方法

     

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

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

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

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

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

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

具体代码如下:

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

     

  2. 实现MQ发送的service
    1. package com.mail.service.impl;
    2. import com.alibaba.fastjson.JSON;
    3. import com.mail.model.MailBean;
    4. import com.mail.service.ActiveMQService;
    5. import org.slf4j.Logger;
    6. import org.slf4j.LoggerFactory;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.beans.factory.annotation.Value;
    9. import org.springframework.jms.core.JmsTemplate;
    10. import org.springframework.stereotype.Service;
    11. @Service
    12. public class ActiveMQServiceImpl implements ActiveMQService {
    13. private Logger logger = LoggerFactory.getLogger(this.getClass());
    14. @Autowired
    15. JmsTemplate template;
    16. @Value("${com.sam.mail.queue}")
    17. private String queueName;
    18. @Override
    19. public void sendMQ(String[] to, String subject, String content) {
    20. this.sendMQ(to,subject,content,null);
    21. }
    22. @Override
    23. public void sendMQ(String[] to, String subject, String content, String filePath) {
    24. this.sendMQ(to,subject,content,filePath,null);
    25. }
    26. @Override
    27. public void sendMQ(String[] to, String subject, String content, String filePath, String srcId) {
    28. MailBean bean = new MailBean();
    29. bean.setTo(to);
    30. bean.setSubject(subject);
    31. bean.setContent(content);
    32. bean.setFilePath(filePath);
    33. bean.setSrcId(srcId);
    34. template.convertAndSend(queueName,bean);
    35. logger.info("邮件已经发送到MQ:"+ JSON.toJSONString(bean));
    36. }
    37. }

     

  3. 实现消息发送的controller
    1. package com.mail.controller;
    2. import com.mail.service.ActiveMQService;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. import javax.annotation.Resource;
    7. /**
    8. * @author JAVA开发老菜鸟
    9. */
    10. @RestController
    11. public class MailSenderController {
    12. @Resource
    13. ActiveMQService activeMQService;
    14. @Value("${mail.to}")
    15. private String mailTo;
    16. @RequestMapping("/sendSimpleMail.do")
    17. public void sendSimpleMail(){
    18. String[] to = {mailTo};
    19. String subject = "普通邮件";
    20. String context = "你好,这是一封普通邮件";
    21. activeMQService.sendMQ(to, subject, context);
    22. }
    23. @RequestMapping("/sendAttachMail.do")
    24. public void sendAttachMail(){
    25. String[] to = {mailTo};
    26. String subject = "带附件的邮件";
    27. String context = "<html><body>你好,<br>这是一封带附件的邮件,<br>具体请见附件</body></html>";
    28. String filePath = "D:\\1.jpg";
    29. activeMQService.sendMQ(to, subject, context, filePath);
    30. }
    31. @RequestMapping("/sendMimeMail.do")
    32. public void sendMimeMail(){
    33. String[] to = {mailTo};
    34. String subject = "普通邮件";
    35. String filePath = "D:\\1.jpg";
    36. String resId = "1.jpg";
    37. String context = "<html><body>你好,<br>这是一封带图片的邮件,<br>请见图片<br><img src=\'cid:"+resId+"\'></body></html>";
    38. activeMQService.sendMQ(to, subject, context, filePath, resId);
    39. }
    40. }

     

  4. MailBean的具体实现
    1. public class MailBean implements Serializable {
    2. private String from;//发件人
    3. private String[] to;//收件人列表
    4. private String subject;//邮件主题
    5. private String content;//邮件正文
    6. private String filePath;//文件(图片)路径
    7. private String srcId;//图片名
    8. ......
    9. getter/setter
    10. ......
    11. }

     

  5. 消费者监听实现
    1. package com.mail.listener;
    2. import com.mail.model.MailBean;
    3. import com.mail.service.MailService;
    4. import org.slf4j.Logger;
    5. import org.slf4j.LoggerFactory;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.jms.annotation.JmsListener;
    8. import org.springframework.stereotype.Service;
    9. import javax.jms.ObjectMessage;
    10. import java.io.Serializable;
    11. /**
    12. * 监听到MQ后调用mailService执行邮件发送操作
    13. */
    14. @Service
    15. public class SendMailMQListener {
    16. Logger logger = LoggerFactory.getLogger(this.getClass());
    17. @Autowired
    18. MailService mailService;
    19. /**
    20. * 通过监听目标队列实现功能
    21. */
    22. @JmsListener(destination = "${com.sam.mail.queue}")
    23. public void dealSenderMailMQ(ObjectMessage message){
    24. try{
    25. Serializable object = message.getObject();
    26. MailBean bean = (MailBean) object;
    27. mailService.sendMail(bean.getTo(),bean.getSubject(),bean.getContent(),bean.getFilePath(),bean.getSrcId());
    28. logger.error("消费者消费邮件信息成功");
    29. } catch (Exception ex){
    30. logger.error("消费者消费邮件信息失败:"+ ex);
    31. }
    32. }
    33. }

     

  6. 监听器调用的发送接口在前面没有,是新加的
    1. @Override
    2. public void sendMail(String[] to, String subject, String context, String filePath, String resId ){
    3. MimeMessage message = mailSender.createMimeMessage();
    4. try{
    5. MimeMessageHelper helper = new MimeMessageHelper(message, true);
    6. helper.setFrom(from);
    7. helper.setTo(to);
    8. helper.setSubject(subject);
    9. helper.setText(context, true);
    10. if(!StringUtils.isEmpty(filePath) && !StringUtils.isEmpty(resId)){//文件路径和resId都不为空,视为静态图片
    11. FileSystemResource resource = new FileSystemResource(new File(filePath));
    12. helper.addInline(resId, resource);
    13. } else if(!StringUtils.isEmpty(filePath)){//只有文件路径不为空,视为附件
    14. FileSystemResource resource = new FileSystemResource(new File(filePath));
    15. helper.addAttachment(resource.getFilename(),resource);
    16. }
    17. mailSender.send(message);
    18. logger.info("邮件发送成功");
    19. } catch (Exception ex){
    20. logger.error("邮件发送错误:", ex);
    21. }

     

  7. 启动工程,分别调用controller中的uri,查看结果

     

  8. 查看下mq的页面控制台

     

 至此,功能已经实现。

三、遇到过的问题

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

第一个问题:

  1. 消费者消费邮件信息失败: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的序列化和反序列化,但是这个过程被认为是不安全的。具体信息查看报错后面的那个网址:

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

解决方法:

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

  1. spring.activemq.packages.trust-all=true

 

第二个问题:

  1. ***************************
  2. APPLICATION FAILED TO START
  3. ***************************
  4. Description:
  5. A component required a bean of type 'com.mail.service.ActiveMQService' that could not be found.
  6. Action:
  7. 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实现异步邮件发送的全部内容了,

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

 

版权声明:本文为sam-uncle原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sam-uncle/p/11032453.html