将 JavaMail 与 SSL 和 TLS 结合使用

Using JavaMail with SSL and TLS

我正在使用 simple-java-mail API,它是 JavaMail API 之上的包装器。 我正在发送带有我的 Gmail 帐户凭据的电子邮件。 我说的是我能做什么,不能做什么。

我可以使用以下设置和属性完美地发送电子邮件。

boolean enableSSL = true;
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", 465);

props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.ssl.enable", enableSSL);
If(enableSSL == true)
    transportStrategy = TransportStrategy.SMTP_SSL;

我无法使用纯 SMTP 发送电子邮件。

    boolean enableSSL = false;
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", 25);
    if(enableSSL == false)
        transportStrategy = TransportStrategy.SMTP_PLAIN;

我无法使用 TLS 设置发送电子邮件。

boolean enableSSL = true;
boolean enableTLS = true;
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.ssl.enable", enableSSL);
props.put("mail.smtp.starttls.enable", true);
If(enableSSL == true && enableTLS == true)
    transportStrategy = TransportStrategy.SMTP_TLS;

除了这些配置属性,我还应该做什么? 使用设置 smtp.gmail.com:25,代码根本不起作用。使用 smtp.gmail.com:465 和 enableSSL = true,代码就像魅力一样工作。

但是 TLS 不工作。我附上我在所有 3 种情况下遇到的错误。

谢谢,

谢谢大家。问题出在我公司的网络上。网络团队更新了传出 SMTP 请求在端口 25 和 587 上被阻止。使用我的个人 wifi 网络,一切都很好。

所以对于GMAIL,对于GMAIL提供的3个端口,我的设置如下。而且我发现不需要使用 simple-java-mail API.

显式设置会话属性

使用端口 25

boolean enableSSL = false;
boolean enableTLS = true;
String host = "smtp.gmail.com";
int port = 25;
String user = "<gmail_account_username>";
String password = "<gmail_account_password>";
ServerConfig serverConfig = new ServerConfig(host, port, user, password);
TransportStrategy transportStrategy = TransportStrategy.SMTP_TLS;
Mailer mailer = new Mailer(serverConfig, transportStrategy);

使用端口 465

boolean enableSSL = true;
boolean enableTLS = false;
String host = "smtp.gmail.com";
int port = 465;
String user = "<gmail_account_username>";
String password = "<gmail_account_password>";
ServerConfig serverConfig = new ServerConfig(host, port, user, password);
TransportStrategy transportStrategy = TransportStrategy.SMTP_SSL;
Mailer mailer = new Mailer(serverConfig, transportStrategy);

使用端口 587

boolean enableSSL = false;
boolean enableTLS = true;
String host = "smtp.gmail.com";
int port = 587;
String user = "<gmail_account_username>";
String password = "<gmail_account_password>";
ServerConfig serverConfig = new ServerConfig(host, port, user, password);
TransportStrategy transportStrategy = TransportStrategy.SMTP_TLS;
Mailer mailer = new Mailer(serverConfig, transportStrategy);