spring实战之使用RabbitMQ--发送邮件

4 篇文章 0 订阅
4 篇文章 0 订阅

上一篇博客的地址
基于上次RabbitMQ的入门使用,我们接着来发送邮件。
代码基于上一篇的代码,这里不再说明。

1.修改代码

  • 下面是修改后的MQReciever
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
public class MQReciever {

    @Value("15777853671@163.com")   //发送邮箱的地址赋值
    private String from;

    @Autowired
    private JavaMailSender mailSender;  //注入邮箱发送者

    @RabbitListener(queues="emall")  //RabbitMQ监听emall队列的内容
    @RabbitHandler
    public void readMsg(String content){
        System.out.println("Read Msg:"+content);
        System.out.println("*** send email*****");
        SimpleMailMessage mail =new SimpleMailMessage();
        mail.setTo("1761552891@qq.com");  //接收邮件方
        mail.setSubject("spring测试");  //邮件的主题
        mail.setText("测试内容:"+content);  //邮件的内容
        mail.setFrom(from);   //邮件发送方
        mailSender.send(mail);  //发送邮件
        System.out.println("发送完毕!");   //发送后打印提示信息
    }
}

2.需要增加的依赖:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <!--mail-->
        <dependency>
        	<groupId>org.springframework.boot</groupId>
        	<artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

注意首次写完后注入的Java邮件发送对象会标红出错

这是因为你的配置没有成功,需要对application.properties(application.yml)

3.修改配置文件

application.properties

spring.rabbitmq.host=  #修改为自己的路径,默认localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672

#mail
spring.mail.host=smtp.163.com #邮件服务器
spring.mail.username=  #你发送的邮箱地址
spring.mail.password= # 密码去使用的邮箱服务中开启smtp获取
spring.mail.properties.mail.smtp.auth=true  #其它参数
spring.mail.properties.mail.starttls.enable=true
spring.mail.properties.mail.starttls..required=true
spring.mail.protocol=smtp

4.打开邮箱的smtp服务

password的获取需要打开smtp服务,我这里使用的是网易邮箱。
在这里插入图片描述
在这里插入图片描述
任意开启其中的一个服务,按照流程会让你手机扫描发送确认短信。会获取到一个授权密码(只显示一次,记得保存)。
到这里,配置就结束了。

4.测试结果

运行一下吧。
在这里插入图片描述
在这里插入图片描述
打开QQ邮箱(手机可能看不见),我的邮件被放到垃圾箱了。
在这里插入图片描述
测试成功!

Good Bye~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值