Gradle插件通过Gmail实现发送邮件

准备工作

1,enable 2 Step Verification

https://myaccount.google.com/security

Gradle插件通过Gmail实现发送邮件

2,获得16位的应用密码

https://security.google.com/settings/security/apppasswords

代码实现

1,对buildSrc添加javax.mail依赖

在buildSrc目录,添加build.gradle

dependencies {
    implementation 'com.sun.mail:javax.mail:1.6.2'
}

2, 创建session需要的properties

properties = System.getProperties()
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", USERNAME);
properties.put("mail.smtp.password", PASSWORD);//16 application password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.proxy.host", PROXY_HOST)
properties.put("mail.smtp.proxy.port", "8080")

3,创建session发送邮件

        Session session = Session.getDefaultInstance(properties)
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(USERNAME))
        message.setRecipients(Message.RecipientType.TO, "test@test.com")//可以添加多个收件人
        message.setSubject("test subject")
        message.setText("test body")
        Transport transport = session.getTransport("smtp")
        transport.connect("smtp.gmail.com", USERNAME, PASSWORD)
        transport.sendMessage(message, message.getAllRecipients())
        transport.close();

上一篇:数据库服务器资源使用周报


下一篇:WEB安全新玩法 [4] 防护邮箱密码重置漏洞