Avatar billede fredand Forsker
05. november 2014 - 17:19 Der er 2 kommentarer og
1 løsning

How to send email from server through gmail?

Hello guys!

I have a webapplication running at Openshift Free (redhat webhotel).
From this app I would like to send an email through my gmail account with the javax.mail-api.
When I try to run my code-attempts from my developer machine it works fine both with SSL and without SSL.
But when I run this from a JSP-page in my openshift server it does not work. I get this response back from gmail:

534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbs0N
534-5.7.14 -wfEXm3iqKdenfgsums1_oLzBr3toWk44lKCVSpdKHkI2cJpo5ytmXFAU2LVn_4a3wrT-2
534-5.7.14 YUjbzlo4QJZRTxuWxujUOMJW8m5HMbUgHqZp0cBWjGZH-Nr5CZrHql_uZx_6IaEot3NJ-m
534-5.7.14 pBj85PCczPqx2q7NFQ6faPMgDRp7yEXlDAKOEZZ10gjxhQ3NLGFYV-_n9yS2ae49ZQOFHn
534-5.7.14 VTLSwBg> Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 g4sm1374527qas.22 - gsmtp

Below is code without SSL:
[code]
    public static void sendGmail(String to, String subject, String text) throws AddressException, MessagingException
    {
        final String SMTP_HOST = "smtp.gmail.com";
        final String SMTP_PORT = "587";
        final String GMAIL_USERNAME = "xxx@gmail.com";
        final String GMAIL_PASSWORD = "xxx";

        System.out.println("Process Started");

        Properties prop = System.getProperties();
        prop.setProperty("mail.smtp.starttls.enable", "true");
        prop.setProperty("mail.smtp.host", SMTP_HOST);
        prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
        prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
        prop.setProperty("mail.smtp.port", SMTP_PORT);
        prop.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(prop, new Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(GMAIL_USERNAME,
                        GMAIL_PASSWORD);
            }
        });
        session.setDebug(true);


        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(GMAIL_USERNAME));
        message.addRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(text);
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        Transport transport = session.getTransport("smtp");
        transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
    }
[/code]
Below is code with SSL:
[code]   
    public static void sendGmail(String to, String subject, String text) throws AddressException, MessagingException
    {
        String host = "smtp.gmail.com";
        final String GMAIL_USERNAME = "xxx@gmail.com";
        final String GMAIL_PASSWORD = "xxx";
       
        Properties props = new Properties();
        props.put("mail.smtps.host", host);
        props.put("mail.smtps.auth", "true");
        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject(subject);
        msg.setText(text);
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setFrom(new InternetAddress(username));
        msg.setHeader("X-Mailer", "smtpsend");
            msg.setSentDate(new Date());
       
            SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
                       
        try
        {
            t.connect(host, username, password);
            t.sendMessage(msg, msg.getAllRecipients());
        }
        finally
        {
            t.close();
        }
    }
[/code]
As you can see I run my attempts in debug mode for the session so below is the output from my attempts:

The debug output from my developer machine with SSL
[code]
    DEBUG: setDebug: JavaMail version 1.4.2
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
    220 mx.google.com ESMTP ny6sm229296lbb.2 - gsmtp
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

    EHLO fredand
    250-mx.google.com at your service, [90.230.21.163]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
    AUTH LOGIN
    334 VXNlcm5hbWU6
    bm9ycnVkZGVuLnZhZ2ZvcmVuaW5nQGdtYWlsLmNvbQ==
    334 UGFzc3dvcmQ6
    bm9ycnVkZGVuOTc=
    235 2.7.0 Accepted
    DEBUG SMTP: use8bit false
    MAIL FROM:<xxx@gmail.com>
    250 2.1.0 OK ny6sm229296lbb.2 - gsmtp
    RCPT TO:<xxx@hotmail.com>
    250 2.1.5 OK ny6sm229296lbb.2 - gsmtp
    DEBUG SMTP: Verified Addresses
    DEBUG SMTP:  xxx@hotmail.com
    DATA
    354  Go ahead ny6sm229296lbb.2 - gsmtp
    Date: Tue, 4 Nov 2014 15:23:48 +0100 (CET)
    From: xxx@gmail.com
    To: xxx@hotmail.com
    Message-ID: <30266940.0.1415111029890.JavaMail.RPS@fredand>
    Subject: Subject_Tue Nov 04 15:23:48 CET 2014
    MIME-Version: 1.0
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: 7bit
    X-Mailer: smtpsend

    text_Tue Nov 04 15:23:48 CET 2014
    .
    250 2.0.0 OK 1415111029 ny6sm229296lbb.2 - gsmtp
    QUIT
    221 2.0.0 closing connection ny6sm229296lbb.2 - gsmtp
[/code]
The debug output from my openshift server with SSL
[code]
    DEBUG: setDebug: JavaMail version 1.4.4
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
    220 mx.google.com ESMTP 4sm1230842qax.48 - gsmtp
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

    EHLO ex-std-node449.prod.rhcloud.com
    250-mx.google.com at your service, [54.90.46.53]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
    AUTH LOGIN
    334 VXNlcm5hbWU6
    bm9ycnVkZGVuLnZhZ2ZvcmVuaW5nQGdtYWlsLmNvbQ==
    334 UGFzc3dvcmQ6
    bm9ycnVkZGVuOTc=
    534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsvV
    534-5.7.14 5K74amuA1WqDS9CFS1UPmuS3XUVU7lq0Agwb5DPcG69Z5fkYe6RUZrzAKPDWy9tQzq2BDg
    534-5.7.14 1AxC2MmT1D1UXOXLG8cZuf7yKxKEUtaLo79a-fROXRiwCvMaqdvYXhqiIslXDTWJQZVe5W
    534-5.7.14 qYvj9_ov5cziZe3ao5usZ-o58tHCv48yzrRm5SppAESXnvmv35ZLy4U9qF14GLEXHT7Wzj
    534-5.7.14 QuIfn6w> Please log in via your web browser and then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 4sm1230842qax.48 - gsmtp
[/code]

The debug output from my developer machine without SSL
[code]
    DEBUG: setDebug: JavaMail version 1.4.2
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
    220 mx.google.com ESMTP x6sm542099lbj.40 - gsmtp
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

    EHLO fredand
    250-mx.google.com at your service, [90.230.21.163]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "STARTTLS", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    STARTTLS
    220 2.0.0 Ready to start TLS
    EHLO fredand
    250-mx.google.com at your service, [90.230.21.163]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
    AUTH LOGIN
    334 VXNlcm5hbWU6
    bm9ycnVkZGVuLnZhZ2ZvcmVuaW5nQGdtYWlsLmNvbQ==
    334 UGFzc3dvcmQ6
    bm9ycnVkZGVuOTc=
    235 2.7.0 Accepted
    DEBUG SMTP: use8bit false
    MAIL FROM:<xxx@gmail.com>
    250 2.1.0 OK x6sm542099lbj.40 - gsmtp
    RCPT TO:<xxx@hotmail.com>
    250 2.1.5 OK x6sm542099lbj.40 - gsmtp
    DEBUG SMTP: Verified Addresses
    DEBUG SMTP:  xxx@hotmail.com
    DATA
    354  Go ahead x6sm542099lbj.40 - gsmtp
    From: xxx@gmail.com
    To: xxx@hotmail.com
    Message-ID: <27966883.0.1415135485593.JavaMail.RPS@fredand>
    Subject: Subject_Tue Nov 04 22:11:24 CET 2014
    MIME-Version: 1.0
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: 7bit

    text_Tue Nov 04 22:11:24 CET 2014
    .
    250 2.0.0 OK 1415135486 x6sm542099lbj.40 - gsmtp
[/code]
The debug output from my openshift server without SSL
[code]
    DEBUG: setDebug: JavaMail version 1.4.4
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.4]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
    220 mx.google.com ESMTP g4sm1374527qas.22 - gsmtp
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

    EHLO ex-std-node449.prod.rhcloud.com
    250-mx.google.com at your service, [54.90.46.53]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "STARTTLS", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    STARTTLS
    220 2.0.0 Ready to start TLS
    EHLO ex-std-node449.prod.rhcloud.com
    250-mx.google.com at your service, [54.90.46.53]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "CHUNKING", arg ""
    DEBUG SMTP: Found extension "SMTPUTF8", arg ""
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
    AUTH LOGIN
    334 VXNlcm5hbWU6
    bm9ycnVkZGVuLnZhZ2ZvcmVuaW5nQGdtYWlsLmNvbQ==
    334 UGFzc3dvcmQ6
    bm9ycnVkZGVuOTc=
    534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbs0N
    534-5.7.14 -wfEXm3iqKdenfgsums1_oLzBr3toWk44lKCVSpdKHkI2cJpo5ytmXFAU2LVn_4a3wrT-2
    534-5.7.14 YUjbzlo4QJZRTxuWxujUOMJW8m5HMbUgHqZp0cBWjGZH-Nr5CZrHql_uZx_6IaEot3NJ-m
    534-5.7.14 pBj85PCczPqx2q7NFQ6faPMgDRp7yEXlDAKOEZZ10gjxhQ3NLGFYV-_n9yS2ae49ZQOFHn
    534-5.7.14 VTLSwBg> Please log in via your web browser and then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 g4sm1374527qas.22 - gsmtp
[/code]
Do you guys get any clue why this is not working from my openshift server?

Best regards
Fredrik
Avatar billede simonvalter Praktikant
05. november 2014 - 17:50 #1
a little search suggest this as the solution as you might have verify new devices logging in if you enabled this feature.

JavaMail and GMail - javax.mail.AuthenticationFailedException
Gmail may block sending if they detect it is first login try from a device. You will then see

javax.servlet.ServletException: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at
534 5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754
Read the instructions at the link. You will need to login to your Gmail account via web browser first and allow new application to access your account (you will be given information and prompt after logging in) . Then try using the JSP script again and the email should be sent correctly this time.

- See more at: http://www.jvmhost.com/articles/how-to-send-mail-with-javamail-and-tomcat#sthash.rsGZotkj.dpuf
Avatar billede fredand Forsker
07. november 2014 - 12:50 #2
Hello!

I got it to work!
The solution seems to be to activate IMAP in gmail.
Then I got it to work.
Best regards!

Please, Simon, leave a svar so I can reward you!
Avatar billede simonvalter Praktikant
07. november 2014 - 14:36 #3
Thanks :)
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester