gpt4 book ai didi

java - 使用 Java 通过 Gmail 发送的问题

转载 作者:行者123 更新时间:2023-11-30 08:18:05 26 4
gpt4 key购买 nike

我有看似非常简单的代码,可以尝试使用我的 Gmail 帐户从我的 Java 应用程序发送电子邮件。当我运行它时,它崩溃并出现异常 javax.mail.AuthenticationFailedException。这是代码:

    // Recipient's email ID needs to be mentioned.
String to = "fredxya@gmail.com";

// Sender's email ID needs to be mentioned
String from = "johnxyzn@gmail.com";

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("fredxyz@gmail.com","password");
}
});

try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

// Set Subject: header field
message.setSubject("Test Subject");

// Now set the actual message
message.setText("this is a test");

// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
System.out.println (mex) ;
mex.printStackTrace();
}

最佳答案

问题是我在 Gmail 中使用了两步验证。解决方案是使用应用程序特定密码 (ASP):https://accounts.google.com/IssuedAuthSubTokens?hide_authsub=1

关于java - 使用 Java 通过 Gmail 发送的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com