使用带有 TLS 的 JavaMail
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/411331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JavaMail with TLS
提问by dancavallaro
I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use JavaMail to access an SMTP server that requires TLS encryption. Can anyone help with this?
我在 SO 上发现了其他几个关于 JavaMail API 和通过 SMTP 服务器发送邮件的问题,但没有一个讨论使用 TLS 安全性。我正在尝试使用 JavaMail 通过我的工作 SMTP 邮件服务器向自己发送状态更新,但它需要 TLS,而且我在网上找不到任何关于如何使用 JavaMail 访问需要 TLS 加密的 SMTP 服务器的示例。有人能帮忙吗?
采纳答案by Sarat
We actually have some notification code in our product that uses TLS to send mail if it is available.
我们的产品中实际上有一些通知代码,它使用 TLS 发送邮件(如果可用)。
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
您将需要设置 Java Mail 属性。您只需要 TLS,但如果您的 SMTP 服务器使用 SSL,您可能需要 SSL。
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
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");
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props)
.
然后,您可以将其传递给 JavaMail 会话或任何其他会话实例化器,例如Session.getDefaultInstance(props)
.
回答by Sarat
Good post, the line
好帖子,行
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.
如果 SMTP 服务器使用SSL 身份验证,则是强制性的,就像 GMail SMTP 服务器一样。但是,如果服务器使用基于TLS 的纯文本身份验证,则不应存在,因为 Java Mail 会抱怨初始连接是纯文本。
Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.
还要确保您使用的是最新版本的 Java Mail。最近我使用了以前项目中的一些旧Java Mail jars,无法使代码工作,因为登录过程失败。升级到最新版本的Java Mail后,错误原因就很清楚了:是javax.net.ssl.SSLHandshakeException,旧版本的lib中没有抛出。
回答by Brent Matzelle
The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:
上面示例中的设置不适用于我使用的服务器 ( authsmtp.com)。我不断收到此错误:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):
我删除了 mail.smtp.socketFactory 设置,一切正常。最终设置是这样的(没有使用 SMTP 身份验证,我在别处设置了端口):
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");
回答by Renish Khunt
Just use the following code. It is really useful to send email via Java, and it works:
只需使用以下代码。通过 Java 发送电子邮件真的很有用,它的工作原理是:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="[email protected]";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
回答by Benny Bottema
With Simple Java Mail 5.0.0(simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.
使用Simple Java Mail 5.0.0(simplejavamail.org) 非常简单,该库将为您处理所有 Session 属性。
Here's an example using Google's SMTP servers:
以下是使用 Google 的 SMTP 服务器的示例:
Email email = EmailBuilder.startingBlank()
.from("lollypop", "[email protected]")
.to("C.Cane", "[email protected]")
.withSubject("hey")
.withPlainText("We should meet up!")
.withHTMLText("<b>We should meet up!</b>")
.buildEmail();
MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
.buildMailer()
.sendMail(email);
If you have two-factor login turned on, you need to generate an application specific passwordfrom your Google account.
如果您启用了双因素登录,则需要从您的 Google 帐户生成应用程序专用密码。