在具有两种身份验证的gmail帐户中通过java发送电子邮件 [英] Sending email through java in gmail account having two way authentication

查看:28
本文介绍了在具有两种身份验证的gmail帐户中通过java发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个可以向任何指定收件人(gmail)发送电子邮件的功能.我面临的问题是,当我尝试提供在 gmail 中使用两种身份验证的凭据时,我的身份验证失败.使用没有双向身份验证的帐户,它可以正常工作.那么在启用两种身份验证的情况下,我必须做些什么才能使事情发生呢?

I want to make a function which can send email to any specified recipient(gmail). The problem I am facing is my authentication fails when I try to provide credentials which uses two way authentication in gmail. With account having no two way authentication it works fine. So what I have to do to make things happen with two way authentications enabled?

以下是我用来发送电子邮件的代码.

Following is the code which I am using to send email.

public static boolean sendMail(String fromMail, String fromPassword, String toMail, String message) {
        try {
            final String user = fromMail, password = fromPassword;
            Properties prop = new Properties();
            prop.setProperty("mail.smtp.host", "smtp.gmail.com");
            prop.setProperty("mail.smtp.port", "465");
            prop.setProperty("mail.smtp.auth", "true");
            prop.setProperty("mail.smtp.ssl.enable", "true");
//            prop.put("mail.debug", "true");

//            prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            Session sess = Session.getDefaultInstance(prop, new Authenticator() {

                @Override
                protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    return new javax.mail.PasswordAuthentication(user, password);
                }
            });

//            Session sess=Session.getDefaultInstance(prop);

            sess.setDebug(true);

            Message msg = new MimeMessage(sess);

            msg.setFrom(new InternetAddress(fromMail));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
            msg.setText(message);
            msg.setContent(message, "text/html");


            Transport.send(msg);
            return true;
        } catch (MessagingException msgEx) {
            msgEx.printStackTrace();
            return false;
        }
    }

推荐答案

通过在 https:///accounts.google.com/IssuedAuthSubTokens.另请查看此 youtube 视频,了解应用程序特定密码.

By creating an application specific password at https://accounts.google.com/IssuedAuthSubTokens. Also check out this youtube video on application specific passwords.

这篇关于在具有两种身份验证的gmail帐户中通过java发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆