【问题标题】:JavaMail - send authenticated oauth2 smtp mailJavaMail - 发送经过身份验证的 oauth2 smtp 邮件
【发布时间】:2016-11-17 01:29:56
【问题描述】:

我正在尝试使用 JavaMail API 1.5.5 通过 Gmail 服务器发送经过身份验证的电子邮件。

我按照javaMailAPI 1.5.5 site中的教程使用this google tool,但没有成功发送邮件。

这是我所做的:

private static void sendEmail(String _emailBody){
    //used oauth2.py in order to retrieve the access token
    String accessToken = getAccessToken(refresh_token,username,client_id,client_secret);
    // Setup mail server
    Properties props = new Properties();
    props.put("mail.imap.ssl.enable", "true"); // required for Gmail
    props.put("mail.imap.auth.mechanisms", "XOAUTH2");
    Session session = Session.getInstance(props);
    Store store = session.getStore("imap");
    store.connect("imap.gmail.com", username, accessToken);
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(username));
    msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(_email));
    msg.setSubject("some subject");
    msg.setText(_emailBody);
    Transport.send(msg);

} 

我得到以下执行:

com.sun.mail.util.MailConnectException
Couldn't connect to host, port: localhost, 25; timeout -1

我也尝试将属性名称中的 imap 切换为 smtp,但在这种情况下程序卡在了

store.connect("imap.gmail.com", username, accessToken);

我该如何解决?我在网上搜索了答案,但没有找到。

编辑:

与建议的问题不完全相同。我在2016年发布的JavaMailAPI 1.5.5上使用oauth2认证,连接方式不同。旧的不行。

它说存在身份验证问题。另外,我不使用用户名和密码,而是使用谷歌提供的用户名和访问令牌。

【问题讨论】:

  • @DalmTo 不完全是。我在2016年发布的JavaMailAPI 1.5.5上使用oauth2认证,连接方式不同。旧的不行。它说存在身份验证问题。
  • 我还使用用户名和访问令牌而不是用户名和密码进行连接。

标签: java oauth-2.0 smtp jakarta-mail gmail-api


【解决方案1】:

您缺少对 JavaMail API 的一些基本了解。存储用于读取消息,传输用于发送消息。 Gmail are in the JavaMail FAQ 的基本示例。尝试该代码,如果仍然无法正常工作,请使用您正在使用的代码更新您的问题并发布JavaMail debug output

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2011-12-22
    • 2011-05-03
    • 2011-01-17
    • 2022-08-14
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多