无法解决使用Gmail Api和服务帐户发送错误请求400发送电子邮件的情况

时间:2019-02-03 07:43:40

标签: java android gmail-api service-accounts bad-request

在此论坛中对错误请求400的许多答复之后,我用尽了很多方法来解决通过服务帐户以及Gmail API和Oauth发送电子邮件时的问题。我尝试过的每个解决方案似乎都不能改变错误,所以我猜我错过了更高的地方。

步骤:

  • 有关Gmail API指南的代码

  • 设置GCP和Google管理员(按照此步骤启动medium.com/lyfepedia/sending-emails-with-gmail-api-and-python-49474e32c81f)

  • 专门....在Google Cloud Console中为该项目设置服务帐户

  • 已获授权进行域范围访问

  • 已添加到项目的JSON凭证文件中。

  • 在管理控制台中具有服务帐户ID的
  • 授权API客户端,当前提供了可能的范围的每种组合“电子邮件(读/写/发送)https://mail.google.com/https://www.googleapis.com/auth/gmail.send

GCP API仪表板显示正在发出请求,但有100%错误。

应用中返回的错误:

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

我的代码

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();
    }
}

任何想法将不胜感激!

1 个答案:

答案 0 :(得分:0)

您似乎无法从服务帐户发送电子邮件(并且我希望得到纠正,或者应该说希望得到纠正)。相反,您必须模拟在gsuite域中注册的帐户,并在使用 .createDelegate()创建Google凭据时将其包括在内。

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

请参见https://stackoverflow.com/a/54108538/9175763

虽然您可以使用Drive API将驱动器文件夹/文件共享到服务帐户以进行访问,但是您不能将私有Gmail委派给服务帐户。 “错误:您指定的Google帐户地址无效。”

但是,您可以使用g-suite电子邮件别名作为现有g-suite电子邮件的代理。只需在管理控制台中向用户添加别名,然后照常打开您的g-suite电子邮件帐户,转到设置,帐户,将邮件发送为并添加您的别名。然后,您可以将委托设置为您的别名。