gpt4 book ai didi

java - 无法使用 JavaMail api 连接到 Gmail SMTP

转载 作者:行者123 更新时间:2023-12-01 08:02:55 25 4
gpt4 key购买 nike

我编写了以下两个java类 -

public class EmailUtil {

public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");

msg.setFrom(new InternetAddress("no_reply@no_reply.com", "NoReply-NP"));

msg.setReplyTo(InternetAddress.parse("no_reply@no_reply.com", false));

msg.setSubject(subject, "UTF-8");

msg.setText(body, "UTF-8");

msg.setSentDate(new Date());

msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);

System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}


public class TLSEmail {


public static void main(String[] args) {
final String fromEmail = "*****@gmail.com";
final String password = "*****";
final String toEmail = "****@gmail.com";

System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS

//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);

EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");

}


}

当我运行此程序时,出现以下错误 -

javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587; 嵌套异常是: java.net.SocketException:权限被拒绝:连接

我该如何解决这个问题?请帮忙!PS - 我没有使用两步验证提前致谢!

最佳答案

为了让它发挥作用,我有:

  1. 为我的 Gmail 帐户启用了 POP/IMAP。
  2. 允许安全性较低的应用通过此网址访问您的帐户: https://www.google.com/settings/security/lesssecureapps .

我希望这对其他人有帮助。

关于java - 无法使用 JavaMail api 连接到 Gmail SMTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823156/

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