1

Google の Gmail API を使用してメールを送信しようとしましたが、次のエラーが発生し続けました。

API がエラーを返しました: エラー: 'raw' RFC822 ペイロード メッセージ文字列または /upload/* URL 経由でメッセージをアップロードしています


GoogleがNodeJS用に提供したスターターコード(ドキュメント)を使用してセットアップを行いました。

const google = require('googleapis');
const googleAuth = require('google-auth-library');
const Base64 = require('js-base64').Base64;

// ...

// create the email string
const emailLines = [];

emailLines.push("From: \"My Name\" <MY_EMAIL@gmail.com>");
emailLines.push("To: YOUR_EMAIL@uw.edu");
emailLines.push('Content-type: text/html;charset=iso-8859-1');
emailLines.push('MIME-Version: 1.0');
emailLines.push("Subject: New future subject here");
emailLines.push("");
emailLines.push("And the body text goes here");
emailLines.push("<b>And the bold text goes here</b>");
const email =email_lines.join("\r\n").trim(); 

// ...

function sendEmail(auth) {
  const gmail = google.gmail('v1');

  const base64EncodedEmail = Base64.encodeURI(email);
  base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_')
  console.log(base64EncodedEmail);

  gmail.users.messages.send({
    auth: auth,
    userId: "me",
    resource: {
      raw: base64EncodedEmail
    }
  }, (err, response) => {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    console.log(response);
  });
}

authオブジェクトとして描くことができます:

{
  transporter: ...,
  _certificateCache: ...,
  _certificateExpiry: ...,
  _clientId: ...,
  _clientSecret: ...,
  _redirectUri: ...,
  _opts: {},
  credentials: { 
    access_token: ...,
    refresh_token: ...,
    token_type: 'Bearer',
    expiry_date: 1517563087857 
  } 
}

重要なのはaccess_token.


ここにリストされている提案されたソリューションをすでに試しました:

しかし、どれも機能しませんでした。ただし、エンコードされた文字列を Google 独自のドキュメントのプレイグラウンドにコピーして貼り付けると、動作します (ドキュメント):

遊び場

したがって、fetch代わりにリクエストを使用するように変更しましたが、これも機能しました。

fetch(`https://www.googleapis.com/gmail/v1/users/me/messages/send`, {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + `the_access_token_in_auth_obj`,
    'HTTP-Version': 'HTTP/1.1',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    raw: base64EncodedEmail
  })
})
.then((res) => res.json())
.then((res) => console.info(res));

なぜそれが起こったのか誰か説明できますか?それはバグですか、googleapiそれとも何か不足していますか?

4

2 に答える 2