问题
When I use the Gmail API Node.js client to send an email with an attachment larger than 5 MB I get an error "413 Request Entity Too Large".
I first create a string mimeMessage which contains a MIME message of type multipart/mixed. One part of this message is a base64 encoded attachment with a size > 5 MB. Then I try to send it:
gmail = google.gmail({ version: 'v1', auth: authentication });
encodedMimeMessage = Buffer.from(mimeMessage)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
gmail.users.messages.send({
userId: 'me',
resource: { raw: encodedMimeMessage }
}, (err, res) => {
...
});
This results in an error response "413 Request Entity Too Large".
According to the api documentation a resumable upload should be used (https://developers.google.com/gmail/api/guides/uploads#resumable). But the documentation only gives examples for HTTP requests and does not describe how it can be done using the Node.js client. I would like to avoid mixing calls to the google-api-nodejs-client with HTTP requests. If this cannot be avoided I would highly appreciate a good example how to do this in Node.js.
I tried to set uploadType to resumable:
gmailApi.users.messages.send({
userId: 'me',
uploadType: 'resumable',
resource: { raw: encodedMimeMessage }
}, (err, res) => {
...
});
I see from the server response that it ended up in the query string, but it did not solve the problem.
I found examples in PHP (Send large attachment with Gmail API, How to send big attachments with gmail API), Java (https://developers.google.com/api-client-library/java/google-api-java-client/media-upload) and Python (Error 10053 When Sending Large Attachments using Gmail API). But they are using a 'Google_Http_MediaFileUpload', 'MediaHttpUploader' and 'MediaIoBaseUpload' respectively and I do not know how to apply this to the nodejs-client.
I found an example in Python (Using Gmail API to Send Attachments Larger than 10mb) which uses uploadType = 'multipart' and a message that is not base64 encoded. But I always get an error response when I do not base64 encode the message.
回答1:
In case someone else comes across this problem: Do not use the resource.raw
property of the first method argument when sending an email. Instead use the media
property:
const request = {
userId: 'me',
resource: {},
media: {mimeType: 'message/rfc822', body: mimeMessage}
};
gmailApi.users.messages.send(request, (err, res) => {
...
});
The mimeMessage
must not be encoded with base64 in this case. In the resource
you can optionally specify the property threadId
.
const request = {
userId: 'me',
resource: {threadId: '...'},
media: {mimeType: 'message/rfc822', body: mimeMessage}
};
gmailApi.users.messages.send(request, (err, res) => {
...
});
来源:https://stackoverflow.com/questions/55639575/send-large-attachments-5-mb-with-the-gmail-api-node-js-client