用Java发送QQ邮件
程序员文章站
2022-06-19 15:49:39
1. 开启QQ邮箱SMTP服务在QQ邮箱的设置 -> 账户中开启POP3/SMTP服务开启成功后记下生成的授权码(可代替原始密码)2. 简单实例创建一个Maven项目,在pom.xml中加入: com.sun.mail javax.mail ...
1. 开启QQ邮箱SMTP服务
在QQ邮箱的设置 -> 账户中开启POP3/SMTP服务
开启成功后记下生成的授权码(可代替原始密码)
2. 简单实例
创建一个Maven项目,在pom.xml中加入:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
package com.example;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailSender {
public static void main(String[] args) {
final String srcEmail = "xxxxx";
final String authCode = "xxxxx";
String targetEmail = "xxxxx";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(srcEmail,authCode);
}
});
try {
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(srcEmail));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(targetEmail));
mimeMessage.setSubject("JavaEmail");
mimeMessage.setText("Hello World!");
Transport.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
只需要自定义填写前三个字符串即可,分别为发件人邮箱地址、授权码、收件人邮箱地址。
本文地址:https://blog.csdn.net/m0_54213794/article/details/112255192
上一篇: promise 核心封装