Android – send email using JavaMail and oauth2

I'm developing a basic e-mail sender application that only sends e-mail to Gmail. After a while, I came up with the oauth2 vulnerability scheme that Google now needs to use the gettoken () method in the Google authutil API for authentication

I searched the JavaMail code on the Internet and sent an email using the token I retrieved from the API. I found the following code I use now:

package com.provider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import android.util.Log;

import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;

public class GMailOauthSender {
private Session session;

private String mailhost = "smtp.gmail.com";   
private int port = 587;
private String user;   
private String password;   



public SMTPTransport connectToSmtp(String host, int port, String userEmail,
        String oauthToken, boolean debug) throws Exception {

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.sasl.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.imap.auth.login.disable", "true");
    props.put("mail.imap.auth.plain.disable", "true");
    session = Session.getInstance(props);
    session.setDebug(debug);


    final URLName unusedUrlName = null;
    SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
    // If the password is non-null, SMTP tries to do AUTH LOGIN.
    final String emptyPassword = null;
    transport.connect(host, port, userEmail, emptyPassword);

            byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail,
            oauthToken).getBytes();
    response = BASE64EncoderStream.encode(response);

    transport.issueCommand("AUTH XOAUTH2 " + new String(response),
            235);

    return transport;
}

public synchronized void sendMail(String subject, String body, String user,
        String oauthToken, String recipients) {
    try {

        SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
                587,
                user,
                oauthToken,
                true);

        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
                message.setSender(new InternetAddress(user));   
                message.setSubject(subject);   
                message.setDataHandler(handler);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        smtpTransport.sendMessage(message, message.getAllRecipients());   


    } catch (Exception e) {
        //Log.d("test", e.getMessage());
    }

}

Unfortunately, the code doesn't work at all. So far, I've been sticking to it for more than three weeks. What's your suggestion?

resolvent:

It was really painful when I first did this and made it work. Follow these steps

First, you need to set oauth2 for your application in the developer console. For more information, please go to this link

Now you need to add these four files, which will help to send mail in the background. When the user opens the application, the user will be shown the consent screen (the code in the file authactivity. Java), and the application must be allowed to use gmail. This is a one-time activity, which is no longer needed in the future. When performing this operation, the user requests a token from the Google server and will save it in the preferences, So as not to ask the user (authpreferences. Java). After the user approves, you can send mail in the following ways:

GMailSender gMailSender = new GMailSender();
gMailSender.sendMail("hi", "hi", authPreferences.getUser(), authPreferences.getToken(), "somemailid@gmail.com");

github: https://gist.github.com/ranjithnair02/1c6dab7dec51971abfec Links to files in

You also need to add the following jar files to the project:

http://javamail-android.googlecode.com/files/mail.jar

http://javamail-android.googlecode.com/files/activation.jar

http://javamail-android.googlecode.com/files/additionnal.jar

You also need to add the following in androidmanifest. XML

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>