java - 使用Javamail连接到Gmail SMTP服务器忽略了指定的端口,并尝试使用25

标签 java groovy smtp gmail jakarta-mail

我正在尝试在 groovy 脚本中使用 javamail 通过 gmail 发送电子邮件。我在网上看了很多地方,但到目前为止一直无法正常工作。我在运行脚本时遇到的错误是:

DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 25, isSSL false
Caught: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25 (javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?))

它似乎正在尝试使用端口 25,即使我已指定它应该使用端口 587。有谁知道可能导致此问题的原因,我使用 telnet 连接到端口 587 上的 smtp 服务器, Thunderbird 使用 587 端口和 STARTTLS 安全,并且能够使用 smtp 服务器成功发送邮件。这告诉我这不是阻塞的端口或连接问题。这是我用来尝试发送电子邮件的代码:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('email@gmail.com', 'password');
    }
}

def  d_email = "email@gmail.com",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "587", //465,587
        m_to = "email@gmail.com",
        m_subject = "Testing",
        m_text = "This is a test."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport.send(msg)

任何帮助将不胜感激。提前致谢!

-布莱恩

最佳答案

在 Java 中你会做类似的事情:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

注意“smtpS”协议(protocol)。此外,现代 JVM 中不再需要 socketFactory 属性,但您可能需要将 Gmail 的“mail.smtps.auth”和“mail.smtps.starttls.enable”设置为“true”。 'mail.smtps.debug' 也会有帮助。

关于java - 使用Javamail连接到Gmail SMTP服务器忽略了指定的端口,并尝试使用25,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1990454/

相关文章:

Java:如何随机遍历数组?

java - Wildfly - 在主配置文件中找不到 "Connector ' netty”

Java string.replace 不能作为 string.replaceAll

groovy - 在 Groovy 中将集合拆分为子集合

validation - Grails,用于更新的自定义Validatable对象

Java Mail 监听消息 POP3

php - Google Gmail SMTP 设置不允许我使用 PHPMailer 发送电子邮件

c# - SMTP 和 OAuth 2

java - 为什么用WebDriver找不到这个元素?

Jenkins 作业 DSL : How to read Pipeline DSL script from file?