SpringBoot整合邮件发送,并存入redis

引入jar包


		
			org.springframework.boot
			spring-boot-starter-mail
		

首先编写邮件处理的工具类,目前只是测试用,一些参数都是写固定的


/*
 * Copyright @ 2019 com.iflysse.trains
 * 01SpringBoot 上午10:31:29
 * All right reserved.
 *
 */
	
package com.dcx.comm.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: MailUtils
 * @author: cxding
 * @createTime: 2019年4月29日 上午10:31:29
 * @version: v1.0
 */
@Configuration
public class MailUtils {
	public static void sendMail(String to, String emailMsg,String title)
            throws AddressException, MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "SMTP");
        props.setProperty("mail.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");// 指定验证为true

        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("你的邮箱", "你的密码");
            }
        };
        Session session = Session.getInstance(props, auth);
        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("你的邮箱")); // 设置发送者
        message.setRecipient(RecipientType.TO, new InternetAddress(to)); // 设置发送方式与接收者
        message.setSubject(title);
        message.setContent(emailMsg, "text/html;charset=utf-8");
        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }

}

控制层代码

@PostMapping("/sendEmail")
	@ApiOperation(value="发送邮件",response=Result.class)
	public Result sendEmail(@ApiParam(value = "邮件实体", required = true) @RequestBody Email email){
		System.out.println(email);
		return stuService.sendEmail(email.getTo(),email.getEmailMsg(),email.getTitle());
	}

service实现层

先注入工具类

@Autowired
private MailUtils mailUtils;
/**
	 * 发送邮件
	 */
	@Override
	public Result sendEmail(String to,String emailMsg,String title) {
		try {
			mailUtils.sendMail(to, emailMsg,title);
			Destination destination = new ActiveMQQueue("email.queue");
			Map emailParam = new HashMap();
			emailParam.put("emailMsg",emailMsg);
			emailParam.put("title", title);
			emailParam.put("to",to);
			String message = JSON.toJSONString(emailParam);
			utils.sendNorMolMessage(destination, message);
		} catch (MessagingException e) {
		}
		return new Result("发送结束",true);
	}

最后启动后调用该方法,代码不完整,请查看我之前的两篇文章

 

 

你可能感兴趣的:(邮件,ActiveMQ学习)