JAVA实现QQ邮箱推送邮件
文章目录
准备
-
在QQ邮箱主界面开启POP/SMTP服务:设置–账户–开启POP/SMTP服务
开启后会给一个POP3/SMTP服务的授权码,保存好该授权码。 -
我们还需要一个mail.jar ,下载参考下方连接
一、在项目中引入JavaMail包
二、开始实现
1.我们在Service类里面编写一个方法,这个方法接收两个参数:1收件人邮箱 2.要发送的内容
代码如下:
package org.jeecg.modules.EmailPush.service.impl;
import com.sun.mail.util.MailSSLSocketFactory;
import org.jeecg.modules.EmailPush.entity.Emailpush;
import org.jeecg.modules.EmailPush.mapper.EmailpushMapper;
import org.jeecg.modules.EmailPush.service.IEmailpushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
/**
* @Description: 邮箱信息推送
* @Author: 汪杰杰杰杰
* @Date: 2022-04-15
* @Version: V1.0
*/
@Service
public class EmailpushServiceImpl extends ServiceImpl<EmailpushMapper, Emailpush> implements IEmailpushService {
@Autowired
JavaMailSender javaMailSender;
@Override
public Boolean EmailPush(String email, String data) {
Boolean bool = false; //用于判定是否发送成功
//设置发送邮件的主机 smtp.qq.com
String host = "smtp.qq.com";
//1.创建连接对象,连接到邮箱服务器
Properties props = System.getProperties();
//Properties 用来设置服务器地址,主机名 。。 可以省略
//设置邮件服务器
props.setProperty("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
//SSL加密
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
//props:用来设置服务器地址,主机名;Authenticator:认证信息
Session session = Session.getDefaultInstance(props, new Authenticator() {
//通过密码认证信息
protected PasswordAuthentication getPasswordAuthentication() {
//new PasswordAuthentication(用户名, password);
//这个用户名密码就可以登录到邮箱服务器了,用它给别人发送邮件
return new PasswordAuthentication("1526668275@qq.com", "OP3/SMTP服务的授权码");
}
});
try {
Message message = new MimeMessage(session);
//2.1设置发件人:
message.setFrom(new InternetAddress("填写发件人的邮箱"));
//2.2设置收件人 email变量存的是收件人邮箱
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
//2.3邮件的主题
message.setSubject("QQ邮箱信息推送测试");
//2.4设置邮件的正文 第一个参数是邮件的正文内容 第二个参数是:是文本还是html的连接
message.setContent("<h1>来自汪杰杰杰的一条消息:</h1><h3>" + data + "</h3>", "text/html;charset=UTF-8");
//3.发送一封激活邮件
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
bool = true;
return bool;
}
}
PostMan调用测试
效果展示
实现代码
我将该功能实现的源码放进阿里云盘,感兴趣的同学可以自行下载学习