基于spring的RabbitMQ发送QQ邮件

RabbitMQ基本概念:
1.Message:消息,由消息头和消息体组成
2.Publisher:生产者(消息发布者)
3.Exchange:交换器接收生产者发布的消息并传给队列
4.Binding:绑定,基于路由键将交换器和消息队列连接起来的路由规则
5.Queue:消息队列
6.Connection:网络连接,例如TCP
7.Channel:信道,新建或销毁TCP太消耗资源,引入信道以复用一个TCP
8.Consumer:消费者,从消息队列中获取消息的客户端应用
9.Virtual Host:共享相同身份认证和加密环境的独立服务器域
10.Broker:消息队列服务器实体
基于spring的RabbitMQ发送QQ邮件_第1张图片

需要的依赖

 <dependency>
            <groupId>org.springframework.amqpgroupId>
            <artifactId>spring-rabbit-testartifactId>
            <version>2.0.2.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.sun.mailgroupId>
            <artifactId>jakarta.mailartifactId>
            <version>1.6.7version>
        dependency>

xml配置


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <bean id="mailMessageListner" class="com.gwhn.provider.controller.MailMessageListener"/>

    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>

    <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672" username="guest" password="guest" virtual-host="/" requested-heartbeat="60"/>

    <rabbit:admin connection-factory="connectionFactory"/>

    <rabbit:queue name="mailQueue"/>

    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="mailExchange" routing-key="mail.test" message-converter="jsonMessageConverter"/>

    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="mailMessageListner" queue-names="mailQueue"/>
    rabbit:listener-container>

    <rabbit:topic-exchange name="mailExchange">
        <rabbit:bindings>
            <rabbit:binding pattern="mail.*" queue="mailQueue"/>
        rabbit:bindings>
    rabbit:topic-exchange>


beans>

qq邮件发送


package com.gwhn.provider.entity;

import java.io.File;
import java.io.Serializable;

/**
 * @author [email protected]
 * @date 2021/12/17 19:26
 */
public class Mail implements Serializable {
    private static final long serialVersionUID = -9042037000449562479L;
    private String formMail;
    private String descMail;
    private String subject;
    private String content;
    private String contentType;
    private String password;
    private File[] files;
}


package com.gwhn.provider.util;

import com.gwhn.provider.entity.Mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author [email protected]
 * @date 2021/12/21 10:31
 */
public class MailUtil {


    /**
     * 向QQ邮箱发送邮件
     * @param mail
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendQQMail(Mail mail) throws MessagingException, UnsupportedEncodingException {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "smtp.qq.com");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.debug", "true");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.ssl.enable", "true");
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getFormMail(), mail.getPassword());
            }
        });
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(mail.getFormMail()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getDescMail()));
            message.setSubject(mail.getSubject());


            // 是否存在附件
            if (null != mail.getFiles() && mail.getFiles().length > 0) {
                MimeMultipart multipart = new MimeMultipart();

                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(mail.getContent(), mail.getContentType());
                multipart.addBodyPart(contentPart);

                for (File file : mail.getFiles()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataHandler dh2 = new DataHandler(new FileDataSource(file));
                    attachment.setDataHandler(dh2);
                    attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
                    multipart.addBodyPart(attachment);
                }
                multipart.setSubType("mixed");

                message.setContent(multipart);
                message.saveChanges();
            }
            // 普通
            else {
                message.setContent(mail.getContent(), mail.getContentType());
            }

            Transport transport = session.getTransport();
            transport.connect(mail.getFormMail(), mail.getPassword());

            Transport.send(message);
        } catch (UnsupportedEncodingException e) {
            throw e;
        } catch (NoSuchProviderException e) {
            throw e;
        } catch (MessagingException e) {
            throw e;
        }

    }

}

消息发送(生产)

package com.gwhn.provider.controller;

import com.gwhn.provider.entity.Mail;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.mail.MessagingException;
import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * @author [email protected]
 * @date 2021/12/17 20:05
 */
public class Business {

    public void userRegister() throws UnsupportedEncodingException, MessagingException {
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("rabbit.xml");
        RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
        Mail mail = new Mail();

        mail.setFormMail("[email protected]");
        mail.setPassword("xxxx");//申请得到的授权码
        mail.setDescMail("[email protected]");
        mail.setContentType("text/html;charset=UTF-8");
        mail.setSubject("测试邮件发送,含附件");
        mail.setContent("test send mail, 这里是中文");
        File[] files = new File[2];
        files[0] = new File("D:\\download\\记录.txt");
        files[1] = new File("D:\\download\\网站.txt");
        mail.setFiles(files);
        template.convertAndSend(mail);
        ctx.close();
    }

//    public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
//        Business business = new Business();
//        business.userRegister();
//    }
}

消息监听(消费)

package com.gwhn.provider.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gwhn.provider.entity.Mail;
import com.gwhn.provider.util.MailUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

/**
 * @author [email protected]
 * @date 2021/12/17 19:58
 */
public class MailMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        String body = new String(message.getBody());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Mail mail = objectMapper.readValue(body,Mail.class);
            System.out.println("接到邮件消息:"+mail);
            MailUtil.sendQQMail(mail);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

qq邮件授权码获取:设置–>账户–>开启stmp服务
基于spring的RabbitMQ发送QQ邮件_第2张图片

你可能感兴趣的:(消息队列,rabbitmq,spring,java)