本文介绍了通过google api发送邮件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Google的Gmail API发送电子邮件,但我一直收到以下错误消息:






我使用Google为NodeJS提供的入门代码进行了设置(

因此,我改为使用 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 的错误还是我缺少什么?

我遇到了相同的RFC822有效负载消息字符串或通过/ upload / * URL上传消息。 示例指定了一个由google-auth-library引起的版本这个错误。快速入门指定:

  npm install google-auth-library@0.* --save 

当我将其更改为

  npm install google-auth-library  - 保存

它在版本1.3.1和0.12.0 。一旦我改变了代码以应对突发变化,所有事情都开始奏效。最新版本的googleapis也有重大变化。这里是我对quickstart的调整:

package.json

  .... 
依赖关系:{
google-auth-library:^ 1.3.1,
googleapis:^ 26.0 .1

quickstart.js

  var fs = require('fs'); 
var readline = require('readline');
var {google} = require('googleapis');
const {GoogleAuth,JWT,OAuth2Client} = require('google-auth-library');


var SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/ gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];

var TOKEN_DIR =(process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE)+'/.credentials/';
var TOKEN_PATH = TOKEN_DIR +'gmail-nodejs-quickstart.json';

函数authorize(credentials,callback){
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris [0];
var auth = new GoogleAuth();
var oauth2Client = new OAuth2Client(clientId,clientSecret,redirectUrl);

//检查我们以前是否存储过令牌。
fs.readFile(TOKEN_PATH,function(err,token){
if(err){
getNewToken(oauth2Client,callback);
} else {
oauth2Client。 credentials = JSON.parse(token);
callback(oauth2Client);
}
});

$ b $ function getNewToken(oauth2Client,callback){
var authUrl = oauth2Client.generateAuthUrl({
access_type:'offline',
scope:SCOPES
});
console.log('通过访问此URL授权此应用程序:',authUrl);
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
rl.question('从该页面输入代码:',function(code){
rl.close();
oauth2Client.getToken(code,function(err,token) {
if(err){
console.log('尝试检索访问令牌时发生错误,错误);
返回;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});



函数makeBody(to,from,subject,message){
var str = [Content-Type:text / plain; charset = \ UTF-8 \\\\

MIME-Version:1.0 \\\

Content-Transfer-Encoding:7bit \\\

to :,to,\\\

from:,from,\\\

subject:,subject,\\\
\\\

message
] .join('');

var encodedMail = new Buffer(str).toString(base64)。replace(/ \ + / g,' - ')。replace(/ \ // g,'_' );
返回encodedMail;
}

函数sendMessage(auth){
var gmail = google.gmail('v1');
var raw = makeBody('[email protected]','[email protected]','test subject','test message');
gmail.users.messages.send({
auth:auth,
userId:'me',
resource:{
raw:raw
}
},函数(err,response){
console.log(err || response)
});

$ b $ const secretlocation ='client_secret.json'

fs.readFile(secretlocation,function processClientSecrets(err,content){
if(err ){
console.log('加载客户机密钥文件时出错:'+ err);
return;
}
//授权客户端使用加载的凭证,然后调用
// Gmail API。
授权(JSON.parse(content),sendMessage);
});

现在,当我运行时,我收到了回复

  Object {status:200,statusText:OK,headers:Object,config:Object,request:ClientRequest,...} 


I've been trying to send emails using Google's Gmail API and I kept getting the following error:


I did the setup using the starter code Google gave for NodeJS (documentation).

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\" <[email protected]>");
emailLines.push("To: [email protected]");
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);
  });
}

You can picture auth as an object:

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

What matters is the access_token.


I've already tried the solutions proposed which are listed here:

But none of them worked. However, when I copied and pasted the encoded string onto the Playground of Google's own documentation, and it works (documentation):

Therefore, I changed to using a fetch request instead, and it also worked.

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

Can anyone explain why it happened? Is it a bug from googleapi or am I missing something?

解决方案

I ran into the same "RFC822 payload message string or uploading message via /upload/* URL required". The quickstart/nodejs sample specifies a version of google-auth-library that caused this error. The quickstart specifies:

npm install google-auth-library@0.* --save

When I changed this to

npm install google-auth-library -- save

it pulled in version 1.3.1 vs 0.12.0. Everything started working once I changed the code to account for the breaking changes. The latest version of googleapis also has breaking changes. Here is my tweaks to the quickstart:

package.json

 ....
  "dependencies": {
    "google-auth-library": "^1.3.1",
    "googleapis": "^26.0.1"
  }

quickstart.js

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
const {GoogleAuth, JWT, OAuth2Client} = require('google-auth-library');


var SCOPES = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'
];

var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';

function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];
    var auth = new GoogleAuth();
    var oauth2Client = new OAuth2Client(clientId, clientSecret, redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function (err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
        } else {
            oauth2Client.credentials = JSON.parse(token);
            callback(oauth2Client);
        }
    });
}

function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    console.log('Authorize this app by visiting this url: ', authUrl);
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Enter the code from that page here: ', function (code) {
        rl.close();
        oauth2Client.getToken(code, function (err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
                return;
            }
            oauth2Client.credentials = token;
            storeToken(token);
            callback(oauth2Client);
        });
    });
}


function makeBody(to, from, subject, message) {
    var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
        "MIME-Version: 1.0\n",
        "Content-Transfer-Encoding: 7bit\n",
        "to: ", to, "\n",
        "from: ", from, "\n",
        "subject: ", subject, "\n\n",
        message
    ].join('');

    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
        return encodedMail;
}

function sendMessage(auth) {
    var gmail = google.gmail('v1');
    var raw = makeBody('[email protected]', '[email protected]', 'test subject', 'test message');
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {
            raw: raw
        }
    }, function(err, response) {
        console.log(err || response)
    });
}

const secretlocation = 'client_secret.json'

fs.readFile(secretlocation, function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    authorize(JSON.parse(content), sendMessage);
});

Now when I run, I get the response

Object {status: 200, statusText: "OK", headers: Object, config: Object, request: ClientRequest, …}

这篇关于通过google api发送邮件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:41