springboot项目使用rabbitMQ发送邮件

首先想要实现springboot实现rabbitmq发送邮件,那肯定需要准备环境:

1、搭好springboot框架

2、本章内容rabbitmq是win安装的,也可以在Linux系统

3、使用一个没有用的qq,开启smtp服务,将授权码保存,下文需要用到

springboot项目使用rabbitMQ发送邮件_第1张图片

 springboot项目使用rabbitMQ发送邮件_第2张图片

先下载rabbitmq的win版:

Installing on Windows — RabbitMQ

springboot项目使用rabbitMQ发送邮件_第3张图片

 安装步骤这里就不说了,直接来代码吧!

配置文件:

rabbitmq端口一定需要看好,与访问页面端口不一样

server.port=8888
server.address=localhost

#RabbitMQ
spring.rabbitmq.port=5672
spring.rabbitmq.host=localhost
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.publisher-confirm-type=correlated
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.virtual-host=TestHost

mybatis.mapper-locations=classpath:com/atxinxin/mapper/*.xml  #mybatis??

logging.file.name=log.log
logging.pattern.level=debug

 需要用到的依赖:

    
        org.springframework.boot
        spring-boot-parent
        2.2.7.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
        

        
            javax.mail
            mail
            1.4.7
        

        
            com.alibaba
            fastjson
            2.0.32
        

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

    

 接下来就是交换机、队列、路由key:

/**
 * @author weixinxin 2023-07-14
 **/
public class RabbitMqConst {

    //发送邮件交换机
    public static final String EXCHANGE_MAIL = "exchange.mail";
    //发送邮件路由key
    public static final String ROUTING_MAIL = "routing.mail";
    //发送邮件队列
    public static final String QUEUE_MAIL  = "queue.mail";
}

 controller层:

这里的参数都是直接设置了,一般在系统里,发件人等等都是数据库中获取

这里其实就是入口

/**
 * @author weixinxin_ext 2023-07-14
 **/

@RestController
@RequestMapping("/rabbitMq")
public class RabbitMqController {

    @Autowired
    private RabbitMqService rabbitMqService;

    private String user = "[email protected]";//发件人
    private String userTo = "[email protected]";//收件人
    
    //邮件内容参数
    private String userName = "采购部部长";
    private String processName = "请假申请";
    //邮件标题参数
    private String subject = "请假申请";

    @GetMapping("/sentMail")
    public String sendMail(){
        HashMap map = new HashMap<>();
        map.put("user",user);
        map.put("userTo",userTo);
        map.put("userName",userName);
        map.put("processName",processName);
        map.put("subject",subject);
        //转换map类型,要不然消费消息的时候,类型不一样,或者设置一个配置文件
        String json = JSON.toJSONString(map, true);
        rabbitMqService.sentMassageJson(RabbitMqConst.EXCHANGE_MAIL,RabbitMqConst.ROUTING_MAIL,json);
        return "消息发送成功";
    }

}

 service层,发送消息:

/**
 * @author weixinxin 2023-07-14
 **/
@Service
public class RabbitMqService {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public Boolean sentMassageJson(String exchange, String routingKey, String massage){
        rabbitTemplate.convertAndSend(exchange,routingKey,massage);
        return true;
    }

}

完成以上步骤可以实现发送消息:

http://localhost:15672
 

使用自己新建用登录---

springboot项目使用rabbitMQ发送邮件_第4张图片

此时发送成功是这样的,可以查看消息,点击队列名称进入:

springboot项目使用rabbitMQ发送邮件_第5张图片

 获取消息;可以查看你之前发送的消息

接下来就是监听器,并且消费消息啦!

/**
 * @author weixinxin_ext 2023-07-14
 **/
@Component
public class ConfirmReceiver {

    //邮件内容:设置邮件字体样式等等,这里可以当成模板,然后设置一些参数,就可以实现一个模板多个模块使用,参数是内容中 {{xxxx}}
    private String test = "

\n" + "\t{{processName}}: \n" + "

\n" + "

\n" + "\t    您好,{{userName}}已将{{processName}}业务审批通过。请您查收。 \n" + "

\n" + "

\n" + "\t
\n" + "

\n" + "

\n" + "\t本邮件由系统自动发送" + "," + "请勿直接回复!若对邮件上述内容有疑问请联系系统管理人员! \n" + "

"; //邮件标题以及参数 private String subject2 = "{{subjectParam}}系统通知"; /** *@Description 发送邮件,消费消息 *@author weixinxin *@Date 11:55 2023/7/17 **/ @SneakyThrows @RabbitListener(bindings = @QueueBinding( value = @Queue(value = RabbitMqConst.QUEUE_MAIL, durable = "true", autoDelete = "false"), exchange = @Exchange(value = RabbitMqConst.EXCHANGE_MAIL), key = (RabbitMqConst.ROUTING_MAIL) )) public void confirmMail(String msg, Message message, Channel channel) { System.out.println("msg = " + msg); Map map = JSON.parseObject(msg, Map.class); try { // 邮箱授权码 String password = "xxxxxxxxxx"; // SMTP服务器地址 String smtpHost = "smtp.qq.com"; // SSL加密的SMTP端口号 int smtpPort = 465; System.out.println("user = " + map.get("user")); Properties properties = new Properties(); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.ssl.enable", "true"); //创建认证器对象和发送者邮箱和授权码 Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(map.get("user"), password); } }); MimeMessage mimeMessage = new MimeMessage(session); //发件人 mimeMessage.setFrom(new InternetAddress(map.get("user"))); //收件人 mimeMessage.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(map.get("userTo"))); //标题,处理参数 mimeMessage.setSubject(this.subject(subject2,map)); //内容,处理参数 mimeMessage.setText(this.content(test,map),"utf-8","html"); // 发送邮件 Transport.send(mimeMessage); System.out.println("邮件发送成功!"); //手动确认 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (MessagingException e) { System.out.println("消息没有消费掉 = = = = = = = = "); //拒绝确认,返回队列 channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); } } /** *@Description 处理标题参数 *@author weixinxin *@Date 11:54 2023/7/17 **/ private String subject(String subject2, Map map) { subject2 = subject2.replace("{{" + "subjectParam" + "}}",map.get("subject")); return subject2; } /** *@Description 处理邮件内容参数 *@author weixinxin *@Date 11:55 2023/7/17 **/ private String content(String test, Map map) { Set keys = map.keySet(); for (String key : keys) { test = test.replace("{{" + key + "}}", map.get(key)); } return test; } }

 效果:

springboot项目使用rabbitMQ发送邮件_第6张图片

你可能感兴趣的:(rabbitmq,spring,boot,java-rabbitmq,rabbitmq)