1

I have what appears to be very simple code to try and send an email from my Java app using my Gmail account. When I run it, it crashes with the exception javax.mail.AuthenticationFailedException. Here is the code:

    // Recipient's email ID needs to be mentioned.
    String to = "[email protected]";

    // Sender's email ID needs to be mentioned
    String from = "[email protected]";

    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("[email protected]","password");
            }
        });

    try{
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO,
                  new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("Test Subject");

        // Now set the actual message
        message.setText("this is a test");

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    }catch (MessagingException mex) {
        System.out.println (mex) ;
        mex.printStackTrace();
    }

2 Answers 2

1

Issue was that I was using 2 step verification in Gmail. Solution is to use an application specific password (ASP): https://accounts.google.com/IssuedAuthSubTokens?hide_authsub=1

Sign up to request clarification or add additional context in comments.

Comments

0

I was able to use gmail to send messages using TLS, with the following properties:

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

perhaps it will work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.