【问题标题】:Need to make Javamail more secure for gmail authentication需要使 Javamail 对 gmail 身份验证更安全
【发布时间】:2016-01-23 18:21:14
【问题描述】:

我已经编写了一个从 java(javamail/jaf) 发送简单邮件的代码。运行该程序后,我收到了来自谷歌的电子邮件,说我的帐户正在被不安全的设备/应用程序访问。然后我不得不更改我的 gmail 帐户的设置以允许登录“不太安全的应用程序”选项。然后我收到了来自该程序的电子邮件。

我需要在不更改帐户中允许“不太安全的应用程序”选项的情况下发送电子邮件。请帮忙。

我的代码是:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("*****@gmail.com","*******");
                }
            });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("*****@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("*****@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear User," +
                    "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

【问题讨论】:

    标签: java email smtp gmail jakarta-mail


    【解决方案1】:

    Gmail 避免这种情况的唯一方法是使用 OAuth 2.0 身份验证。您可以通过此链接了解它。 https://developers.google.com/gmail/xoauth2_protocol?hl=en

    【讨论】:

    • 我不知道为什么我只有一个链接的答案被删除了,但这个只有一个链接的答案没有被删除。无论如何,您可以找到更多关于将 OAuth2 与 JavaMail here 结合使用的信息。
    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多