javax.mail
依赖__javax.mail + mq
<!--javax.mail-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!--activeMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
application.properties
#ActiveMQ
spring.activemq.broker-url=tcp://localhost:61616
场景:
用户注册时,需要给用户发送邮件,采用ActiveMQ作为消息中间件
Controller 中的 Producer
//注入JmsTemplate
@Autowired
private JmsTemplate jmsTemplate;
@RequestMapping("/register")
public String register(HttpServletRequest request) throws MessagingException {
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
String email = request.getParameter("email");
User user = new User();
user.setUserName(userName);
user.setPassWord(passWord);
user.setEmail(email);
user.setState("0");
user.setCreateTime(new Date());
userService.addUser(user);
// MailUtils.sendMail(email,"欢迎您成为我们的会员");
/**
* MQ
*/
jmsTemplate.send("mail_lp", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("title","注册邮件");
message.setString("email",email);
return message;
}
});
return "/success";
}
Consumer
消费类上必须有 @Component 或者@Service 注解,这样Consumer才会委派给Listener.
@Component
public class Consumer {
@JmsListener(destination = "mail_lp")
public void sendMail(Message message) throws JMSException, MessagingException {
MapMessage mm = (MapMessage) message;
String title = mm.getString("title");
String email = mm.getString("email");
MailUtils.sendMail(email,title);
}
}
MailUtils
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.126.com");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//return new PasswordAuthentication("CalistaAngel", "lp123456");给你们用我的问题也不大毕竟我不是那么小气的人哈哈哈哈哈
return new PasswordAuthentication("邮箱名", "授权码");
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("CalistaAngel@126.com")); // 设置发送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
message.setSubject("用户注册");
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
}
mq
小礼物走一走,来简书关注我
作者:东篱茶舍
链接:https://www.jianshu.com/p/ed28c88cdea6
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。