Я пытался отправлять электронные письма с помощью 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\" <[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);
});
}
Вы можете представить auth
как объект:
{
transporter: ...,
_certificateCache: ...,
_certificateExpiry: ...,
_clientId: ...,
_clientSecret: ...,
_redirectUri: ...,
_opts: {},
credentials: {
access_token: ...,
refresh_token: ...,
token_type: 'Bearer',
expiry_date: 1517563087857
}
}
Важно то, что access_token
.
Я уже пробовал предлагаемые решения, перечисленные здесь:
- StackOverflow: не удалось отправить почту через API Google с помощью javascript
- ExceptionsHub: не удалось отправить почту через google api в nodejs а>
- StackOverflow: API Gmail для отправки писем в Node.js
Но ни один из них не работал. Однако, когда я скопировал и вставил закодированную строку в Playground собственной документации 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
или я что-то упустил?