java - 通过 JavaMail 发送到 gmail 时的 TLS 问题

标签 java email smtp gmail jakarta-mail

事实证明,JavaMail 比我想象的更令人沮丧。我看过几个在线示例,了解如何通过 Gmail 的服务器(但不是通过 SSL)发送简单的 SMTP 电子邮件。在尝试了几个不同的代码示例之后,我在调用 transport.connect() 时一直得出相同的示例异常。我不断得到这个堆栈跟踪:

Exception in thread "main" com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. l10sm302158wfk.21
     at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
     at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)
     at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)
     at SendEmail.main(SendEmail.java:47)

有人可以告诉我应该添加什么或做些什么来解决这个问题吗?

这是我的代码:

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.host", "smtp.gmail.com");
    props.put("mail.user", "blahblah@gmail.com");
    props.put("mail.password", "blah");
    props.put("mail.port", "587");

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("This is a test");
    message.setContent("This is a test", "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("blahblah2@gmail.com"));

    transport.connect();
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();

最佳答案

您需要启用 STARTTLS。在您的配置中再添加一项属性:

props.put("mail.smtp.starttls.enable", "true");

关于java - 通过 JavaMail 发送到 gmail 时的 TLS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6512430/

相关文章:

java - 将 java.time.LocalDate 与 postgres 日期进行比较时出现问题

java - 递归反向链表,最后一个节点应该指向null吗?

vb.net - 使用简单的 .net 应用程序发送邮件时出现问题。服务器拒绝错误

java - jsonchema2pojo : How the minLength, maxLength 边界应用于生成的 Java Pojo 类?

java - 将 IP 地址存储在 UserDetails 实例中

javascript - 尝试从函数返回有效的电子邮件

python - InboundEmailMessage 引发 UnicodeDecodeError 异常

python - 当正文中有 unicode 字符时,使用 python 解析 Gmail 电子邮件

.net - 在 ASP.NET 应用程序中存储 SMTP 凭据的最佳实践是什么?

ruby-on-rails - Sendgrid 上的 Heroku 错误