我的nodejs程序无法使用Gmail api发送消息。
GmailAPI在Node. js中发送邮件的解决方案对我不起作用。
我用
var {google} = require('googleapis');
// to and from = "some name <blaw.blaw.com"
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\r\n",
"MIME-Version: 1.0\r\n",
"Content-Transfer-Encoding: 7bit\r\n",
"to: ", to, "\r\n",
"from: ", from, "\r\n",
"subject: ", subject, "\r\n\r\n",
message
].join('');
encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
然后转到GoogleAPI资源管理器https://developers.google.com/apis-explorer/#p/输入gmail. user.message.send和上述make_body生成的字符串。
一封电子邮件将成功发送。所以我知道上面的编码是可以的。
当我的程序尝试使用以下方式发送时,它失败并出错
错误:RFC822有效负载消息字符串或通过 /upload上传消息/*URL需要
function sendMessage(auth) {
var gmail = google.gmail('v1');
var raw = makeBody('john g <asdfasdf@hotmail.com>', 'john g<asfasdgf@gmail.com>', 'test subject', 'test message #2');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
}
身份验证令牌很好,因为我可以调用gmail. user.labels.list,并且在使用API资源管理器时使用相同的授权。
Q1:有人知道为什么上面的行不通吗?
Q2:用于在Node. js中发送邮件的GmailAPI并不能解释为什么原始电子邮件消息被包装在资源字段中。我简单地尝试了原始邮件,但没有帮助。
这失败了。
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
也是如此
gmail.users.messages.send({
auth: auth,
userId: 'me',
raw: raw
}, function(err, response) {
console.log(err || response)
});
这个GMAILAPI发送带有附件的电子邮件
gmail.users.messages.send({
auth: auth,
userId: 'me',
data: raw
}, function(err, response) {
console.log(err || response)
});
有人知道它记录了如何传递api资源管理器要求的“请求的主体”吗?
Q3:为什么google api需要base64编码的替换?
我尝试使用编码
const Base64 = require("js-base64").Base64
var encodedMail = Base64.encode(str);
当我把这个输入API浏览器时,我得到了错误
"message":"ByteString的值无效:
Ohai!对于在这里跌倒的其他人,有几件事。首先-我们现在在这里有一个完整的端到端发送邮件示例:
https://github.com/google/google-api-nodejs-client/blob/master/samples/gmail/send.js
其次,上面的答案基本上是正确的:)而不是安装最新版本的google-auth-Library
…只是把它从你的pack. json中删除。入门指南非常非常错误(它已经被修复了)。googelapis
引入了它自己兼容的google-auth-Library
版本,所以你真的不想因为安装自己的版本而弄乱它:)
快速入门指定:
npm install google-auth-library@0.* --save
当我把这个改成
npm install google-auth-library -- save
它引入了1.3.1 vs 0.12.0版本。一旦我更改代码以解释重大更改,一切都开始工作。最新版本的googleapis也有重大更改。这是我对快速入门的调整:
包. json
....
"dependencies": {
"google-auth-library": "^1.3.1",
"googleapis": "^26.0.1"
}
快速入门. 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('xxxxxxxx@hotmail.com', 'xxxxxxx@gmail.com', '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);
});
现在当我跑的时候,我得到了回应
Object {status: 200, statusText: "OK", headers: Object, config: Object, request: ClientRequest, …}