无法通过SMTP服务器

时间:2018-01-21 04:11:24

标签: java javamail

当我尝试从(sp@gmail.com)的个人电子邮件中 java 发送邮件时,它会成功发送。

但是当我使用我的公司电子邮件(sp@example.com)时,它会抛出Authentication failed exception。我正在使用 TLS身份验证,并且已成功连接到主机。

当我手动登录我的电子邮件时,它总是要求两步 验证即可。即使我已禁用我的两步验证并且还进行了更改以降低安全性,它仍然要求进行两步验证,因为它在显示此用户名和密码后显示此消息:

2-Step Verification
Based on your organization's policy, you need to turn on 2-step verification. Contact your administrator to learn more.
Enter one of your 8-digit backup codes

在这种情况下,我该怎么办?由于这是我在这家公司的第一项任务,如果你能帮助我,我会很高兴。我怎么能解决这个问题?

我的代码:

String to = "abc@example.com";
String user = "sp@example.com";
String pass = "1234";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); 
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication() 
    {
        return new PasswordAuthentication(user,pass);
    }
});

session.setDebug(true);

try
{
    /* Create an instance of MimeMessage, 
        it accept MIME types and headers 
        */
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(user));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
    message.setSubject(sub);
    message.setText(msg);
    /* Transport class is used to deliver the message to the recipients */ 
    Transport.send(message);
}
catch(Exception e)
{
    e.printStackTrace();
}

错误讯息:

535 5.7.3 Authentication unsuccessful javax.mail.AuthenticationFailedException at javax.mail.Service.connect(Service.java:319) at javax.mail.Service.connect(Service.java:169) at javax.mail.Service.connect(Service.java:118) at javax.mail.Transport.send0(Transport.java:188) at javax.mail.Transport.send(Transport.java:118) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPo‌​olExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.r‌​un(TaskThread.java:6‌​1) at java.lang.Thread.run(Thread.java:748)

SMTP配置:

configuration:props.put("mail.smtp.host", "smtp.oceaneering.com"); props.put("mail.smtp.port", "587"); 
props.put("mail.smtp.auth", "true"); 
props.put("mail.smtp.starttls.enable", "true");

1 个答案:

答案 0 :(得分:0)

  1. 首先需要打开两步验证。(之后,该Google脚本为创建应用密码提供了新选项)https://support.google.com/accounts/answer/185839
  2. 接下来,您必须创建应用密码https://support.google.com/accounts/answer/185833?hl=en
  3. 在代码中替换此行的最后一步 字符串传递=“ 1234”; -使用应用专用密码(必须在步骤2上生成),例如String pass =“ djd5n7hsd”;

    对于将来的读者来说,检查系统上的网络和防火墙设置以及通过邮件发送ISP可能会很有用。要检查数据包是否可以到达gmail服务器。 尝试telnet命令:telnet smtp.gmail.com 587