Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email through java in gmail account having two way authentication

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;
        }
    }
like image 871
Ankur Trapasiya Avatar asked Dec 23 '11 21:12

Ankur Trapasiya


1 Answers

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

like image 149
Friek Avatar answered Sep 30 '22 10:09

Friek