Java如何通过SSL使用Gmail发送电子邮件?

在另一个示例中,您已经了解了如何通过TLS使用Gmail SMTP发送电子邮件。请参阅以下示例,如何通过TLS使用Gmail发送电子邮件?

在此示例中,您将使用SSL连接来连接到Gmail SMTP服务器。与的区别在于我们用于创建邮件会话对象的属性/配置。

package org.nhooo.example.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class GmailSendEmailSSL {
    private static final String USERNAME = "nhooo";
    private static final String PASSWORD = "********";

    public static void main(String[] args) throws Exception {
        // 电子邮件信息,例如从,到,主题和内容。
        String mailFrom = "nhooo@gmail.com";
        String mailTo = "nhooo@gmail.com";
        String mailSubject = "SSL - Gmail Send Email Demo";
        String mailText = "SSL - Gmail Send Email Demo";

        GmailSendEmailSSL gmail = new GmailSendEmailSSL();
        gmail.sendMail(mailFrom, mailTo, mailSubject, mailText);
    }

    private void sendMail(String mailFrom, String mailTo, String mailSubject,
                          String mailText) throws Exception {

        Properties config = createConfiguration();

        //创建一个邮件会话。我们需要提供用户名和
        // Gmail验证的密码。
        Session session = Session.getInstance(config, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    GmailSendEmailSSL.USERNAME,
                    GmailSendEmailSSL.PASSWORD
                );
            }
        });

        // 创建电子邮件
        Message message = new MimeMessage(session);
        message.setSentDate(new Date());
        message.setFrom(new InternetAddress(mailFrom));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        message.setSubject(mailSubject);
        message.setText(mailText);

        // 发送消息
        Transport.send(message, GmailSendEmailSSL.USERNAME, GmailSendEmailSSL.PASSWORD);
    }

    private Properties createConfiguration() {
        return new Properties() {{
            put("mail.smtp.host", "smtp.gmail.com");
            put("mail.smtp.auth", "true");
            put("mail.smtp.port", "465");
            put("mail.smtp.socketFactory.port", "465");
            put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }};
    }
}

您可能会收到一条错误消息,提示您无法连接到smtp.gmail.com端口465。在这种情况下,请使用telnet命令检查您与服务器的连接。命令为telnet smtp.gmail.com 465,看看是否有答复。

Maven依赖

<!-- http://repo1.maven.org/maven2/javax/mail/javax.mail-api/1.5.6/javax.mail-api-1.5.6.jar -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.5.6</version>
</dependency>
<!-- http://repo1.maven.org/maven2/javax/mail/mail/1.4.7/mail-1.4.7.jar -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>