上一篇博客的地址
基于上次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.修改配置文件
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邮箱(手机可能看不见),我的邮件被放到垃圾箱了。
测试成功!