使用OAuth2协议进行认证,并指定全范围(mail scope)来发送邮件。以下是示例代码:
import java.util.;
import javax.mail.;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String [] args) {
String to = "recipient@gmail.com"; // 收件人邮箱地址
String from = "sender@gmail.com"; // 发件人邮箱地址
String host = "smtp.gmail.com"; // Gmail SMTP服务器地址
String clientId = "your-client-id"; // 客户端ID
String clientSecret = "your-client-secret"; // 客户端密钥
String refreshToken = "your-refresh-token"; // 刷新令牌
// 设置OAuth2认证
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); // 使用TLS加密
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587"); // Gmail SMTP端口号
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, null);
}
protected OAuth2Authenticator getOAuth2Authenticator() {
return new OAuth2Authenticator(clientId, clientSecret, refreshToken);
}
});
try {
// 创建邮件消息
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("JavaMail OAuth2 test");
message.setText("This is a test message sent via JavaMail OAuth2.");
// 发送邮件
Transport.send(message);
System.out.println("Message sent successfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
class OAuth2Authenticator extends Authenticator {
private String clientId;
private String clientSecret;
private String refreshToken;
public