JAVA实现使用QQ邮箱发送验证码功能
QQ邮箱设置
-
第一步 ,打开QQ邮箱(地址:登录QQ邮箱);
-
第二步 ,登录后点击设置
-
第三步,点击账户,下拉找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
打开Pop3/SMPT服务 ,获取邮箱授权码(需要手机验证) -
第五步,开启成功后会获得一个授权码,记录下来(代码中需要使用,这个授权码并不是一定的 )
导入依赖jar包
-
分别是:activation.jar、commons-email-1.x.jar、mail.jar
原创作者已经整合好了,地址:java发送email依赖jar包_java发送邮件jar包依赖-Java工具类资源-CSDN下载
发送邮件代码
随机生成六位验证码方法:
int verificationCode = (int) ((Math.random() * 9 + 1) * 100000);
public void sendMail(){
String[] receivers = {"邮箱@163", "邮箱@qq"};
List<File> fileList = new ArrayList<>();
if(receivers != null && receivers.length > 0){
try{
Properties properties = new Properties();
//企业邮箱使用:smtp.exmail.qq
properties.put("mail.smtp.host", "smtp.qq");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
MimeMessage message = new MimeMessage(session);
// 发件人
message.setFrom(new InternetAddress("发件人邮箱@qq"));
// 收件人(多个)
InternetAddress[] sendTo = new InternetAddress[receivers.size()];
for (int i = 0; i < receivers.size(); i++) {
sendTo[i] = new InternetAddress(receivers.get(i));
}
message.setRecipients(MimeMessage.RecipientType.TO, sendTo);
// 邮件主题
// message.setSubject("邮件主题");
message.setSubject(title,"UTF-8")
// 添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent("邮件内容", "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 遍历添加文件附件
if (fileList != null && fileList.size() > 0) {
for (File file : fileList) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", "B"));
multipart.addBodyPart(attachmentBodyPart);
}
}
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport();
//或者为企业邮箱和密码
transport.connect("发件人邮箱@qq", "授权码");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch (Exception e) {
e.printStackTrace();
}
}
更多推荐
Java 实现邮箱发送验证码——QQ邮箱为例
发布评论