JavaMail提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API可以方便地执行一些常用的邮件传输。可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。本文主要介绍Java 中使用JavaMail通过Gmail发送电子邮件。

1、引用JavaMail

pom.xml中添加依赖如下,

    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>

参考文档:https://javaee.github.io/javamail/

2、使用Gmail SMTP的TLS

1)SMTP的url和port

SMTP = smtp.gmail.com 
Port = 587

2)实现代码

package com.cjavapy;

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

public class SendEmailTLS {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "password";

        Properties prop = new Properties();
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true"); //TLS
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("to_username_a@gmail.com, to_username_b@163.com")
            );
            message.setSubject("Gmail TLS 测试");
            message.setText("邮件内容,"
                    + "\n\n 测试邮件内容");

            Transport.send(message);

            System.out.println("发送成功");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

3、使用Gmail SMTP的SSL

1)SMTP的url和port

SMTP = smtp.gmail.com 
Port = 465

2)实现代码

package com.cjavapy;

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

public class SendEmailSSL {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "password";

        Properties prop = new Properties();
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("to_username_a@gmail.com, to_username_b@163.com")
            );
            message.setSubject("Gmail SSL 测试");
            message.setText("邮件内容,"
                    + "\n\n 测试邮件内容");

            Transport.send(message);

            System.out.println("发送成功");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

4、Gmail 启用不太安全的应用程序

从 2022 年 5 月 30 日起,Google 不再支持使用第三方应用或设备,这些应用或设备要求仅使用的用户名和密码登录的 Google 帐户。因此,必须为应用程序使用不同的解决方案。为此,需要先为我们的 Gmail 帐户启用两步验证,然后我们可以使用应用密码功能来解决这个问题。

需要要启用两步验证,我们必须:

导航到我们的 Google 帐户 - 将从 (https://myaccount.google.com/) 发送电子邮件的帐户

1)在左侧的菜单中,我们应该选择 Security

2)然后在“登录谷歌”部分下,我们可以看到两步验证已关闭——所以我们必须点击它

3)单击开始,提供您的密码,并通过提供手机号码确认代码

4)如果一切顺利,应该会看到打开选项,因此只需单击它,此时,我们已经启用了两步验证,我们可以返回安全页面。在那里,在相同的“登录谷歌”部分下,我们可以找到应用专用密码选项设置为无。

5)我们必须点击它提供密码,单击选择应用程序菜单,并选择其他(自定义名称)选项,为我们的应用程序提供我们喜欢的任何名称,然后单击“生成”按钮,将为我们生成一个新密码,我们应该在我们的appsettings.json文件中使用它而不是我们的个人密码。

有了这个,我们可以再次使用我们的第三方应用程序发送电子邮件。

参考文档:https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor

推荐文档