0

After following many responses to bad request 400 in this forum, I have run out of options to resolve the issue when sending emails via a service account and Gmail API & Oauth. Every solution I have tried doesn't seem to change the error so I am guessing I missing something higher up.

Steps:

  • followed Gmail api guides for code

  • Set up GCP and Google Admin ( followed this to start medium.com/lyfepedia/sending-emails-with-gmail-api-and-python-49474e32c81f)

  • specifically....set up the service account in Google Cloud Console for the project,

  • authorised for domain wide access,

  • added to the JSON credential file to the project.

  • authorised API clients with the Service Account ID in the admin console, provided every combination of scopes possible currently "Email (Read/Write/Send) https://mail.google.com/, https://www.googleapis.com/auth/gmail.send"

The GCP API dashboard shows requests are being made but with 100% errors.

The error returned in the app:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad 
Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Bad Request",
    "reason" : "failedPrecondition"
  } ],
  "message" : "Bad Request"
}

And my code

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class mod_gmail_send_2 extends AsyncTask<Void, Void, String> {

    private Gmail mGmailService = null;
    private GoogleCredential mCredential;
    private Context mContext;

    private String userID = "me";
    private String emailFrom = "xxxx@gmail.com"; //non specific  account?!?
    private String emailTo = "xxxxx@gmail.com";
    private String emailSubject = "This is the subject";
    private String emailBody = "This is the body text";
    private List<String> scopes = Arrays.asList(GmailScopes.GMAIL_SEND);

    public mod_gmail_send_2(Context myContext) {
        mContext = myContext;
    }

    @Override
    protected String doInBackground(Void... params) {

        try {
            mCredential = GoogleCredential
                    .fromStream(mContext.getResources().openRawResource(R.raw.myjsoncredentials))
                    .createScoped(scopes);
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mGmailService = new Gmail.Builder(transport, jsonFactory, mCredential).build();
            MimeMessage mMimeMessage = createEmail(emailTo, emailFrom, emailSubject, emailBody);
            sendMessage(mGmailService, userID, mMimeMessage);

        }catch(Throwable e){
            return e.getLocalizedMessage();
        }
        return "Success";
    }

    public static Message sendMessage(Gmail service,String userId,MimeMessage emailContent) throws MessagingException, IOException {
        Message message = createMessageWithEmail(emailContent);
        message = service.users().messages().send(userId, message).execute();
        System.out.println("Message id: " + message.getId());
        System.out.println(message.toPrettyString());
        return message;
    }

    public static MimeMessage createEmail(String to,String from,String subject,String bodyText) throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage email = new MimeMessage(session);
        email.setFrom(new InternetAddress(from));
        email.addRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress(to));
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    public static Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        emailContent.writeTo(buffer);
        byte[] bytes = buffer.toByteArray();
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

    @Override
    protected void onPostExecute(String output) {
        Toast.makeText(mContext, output, Toast.LENGTH_LONG).show();
    }
}

Any ideas would be appreciated!!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
plam
  • 313
  • 1
  • 4
  • 17

1 Answers1

0

It appears (and I stand to be corrected, or should I say wish to be corrected) that you cannot send an email from a service account. You must instead impersonate an account registered in your gsuite domain and include it when creating your google credential with .createDelegate().

 GoogleCredential
    .fromStream(service_account_json_credentials)
    .createDelegate(your_impersonated_account@your_domain)
    .createScoped(scopes)

See https://stackoverflow.com/a/54108538/9175763

Whilst you can share drive folder/files to your service account for access using the Drive API, you cannot delegate a private Gmail to your service account. "Error: Google account address you have specified is invalid."

You can however use a g-suite email alias as the delegate from your existing g-suite email. Simply add the alias to the user in the Admin console then open your g-suite email account as normal, go to settings, accounts, send mail as and add your alias. You can then set the delegate to your alias.

plam
  • 313
  • 1
  • 4
  • 17