springboot项目使用rabbitMQ发送邮件

该文详细介绍了如何在Springboot项目中配置RabbitMQ,包括环境搭建、依赖引入、交换机、队列和路由键的设置,以及邮件发送和监听的实现。通过创建控制器和服务层,结合RabbitTemplate发送消息,并使用监听器消费消息,最终实现实时发送邮件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1、搭好springboot框架

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

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

 

先下载rabbitmq的win版:

Installing on Windows — RabbitMQ

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

配置文件:

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

 需要用到的依赖:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-parent</artifactId>
        <version>2.2.7.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.32</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

 接下来就是交换机、队列、路由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 = "xinxin@xxx.com";//发件人
    private String userTo = "xinxin@xxx.com";//收件人
    
    //邮件内容参数
    private String userName = "采购部部长";
    private String processName = "请假申请";
    //邮件标题参数
    private String subject = "请假申请";

    @GetMapping("/sentMail")
    public String sendMail(){
        HashMap<Object, Object> 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
 

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

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

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

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

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

    //邮件内容:设置邮件字体样式等等,这里可以当成模板,然后设置一些参数,就可以实现一个模板多个模块使用,参数是内容中 {{xxxx}}
    private String test = "<p style=\"font-family:微软雅黑;font-size:14px;background-color:#FFFFFF;\">\n" +
            "\t<span style=\"font-family:微软雅黑;font-size:14px;color:#333333;\">{{processName}}:</span><span style=\"font-size:12px;color:#333333;font-family:Verdana, sans-serif;\"></span> \n" +
            "</p>\n" +
            "<p style=\"font-family:微软雅黑;font-size:14px;background-color:#FFFFFF;\">\n" +
            "\t<span style=\"background-color:rgba(0, 0, 0, 0);\">&nbsp; &nbsp; 您好,{{userName}}已将{{processName}}业务审批通过。请您查收。</span> \n" +
            "</p>\n" +
            "<p style=\"font-family:微软雅黑;font-size:14px;background-color:#FFFFFF;\">\n" +
            "\t<br />\n" +
            "</p>\n" +
            "<p style=\"font-family:微软雅黑;font-size:14px;background-color:#FFFFFF;\">\n" +
            "\t<span style=\"font-family:&quot;font-size:14px;background-color:#FFFFFF;color:#999999;line-height:1;\">本邮件由系统自动发送</span>" +
            "<span style=\"font-family:&quot;font-size:14px;background-color:#FFFFFF;color:#999999;line-height:1;\">," +
            "</span><span style=\"font-family:&quot;font-size:14px;background-color:#FFFFFF;color:#999999;line-height:1;\">请勿直接回复!若对邮件上述内容有疑问请联系系统管理人员!</span> \n" +
            "</p>";
    //邮件标题以及参数
    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<String, String> 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<String, String> 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<String, String> map) {
        Set<String> keys = map.keySet();
        for (String key : keys) {
            test = test.replace("{{" + key + "}}", map.get(key));
        }
        return test;
    }

}

 效果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值