Reputation: 1
I have been searching for this for weeks. I just want to be able to send an email with an attachment.
I've been able to send an email, text and html.
I can upload a document to google drive.
I assumed knowing these two things would enable me to reach my end goal, but I cannot for the life of me get an attachment to send through the gmail api.
This question very well may already be on stack overflow, but I have not seen any posts with javascript as the language. And the ones that were did not address sending an email with an attachment.
i dont care if it's through cors or through the gapi.client, i just need it to work.
Any pointers greatly appreciated.
Upvotes: 0
Views: 2190
Reputation: 13
This is what I have achieved so far. I'm using the gapi
client library.
So first you have to construct your emails properly, here's my working example, note that in between any part an empty line is required. You can add all parts into an array and use the your_array.join('\r\n')
to construct the email.
Content-Type: multipart/mixed; boundary="your_boundary"
MIME-Version: 1.0
From: [email protected]
To: [email protected]
Subject: Test
Reply-To: [email protected]
Date: Wed Jan 04 2017 10:47:11 GMT-0500 (EST)
--your_boundary
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<p>Boundary, multi attachs<br />
<em><strong>--<br />
With Regards</strong></em></p>
--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_asc.png"
YOUR_BASE64_ENCODED_DATA
--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_both.png"
YOUR_BASE64_ENCODED_DATA
--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_desc.png"
YOUR_BASE64_ENCODED_DATA
--your_boundary--
Then I'm using gapi's client to send the email; sendMessage
is the function that gapi's online document provides. Before you send email, you need to Base64URL encode your email. I got the encode library from here: https://www.npmjs.com/package/js-base64
sendMessage = function(userId, email, callback) {
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'resource': {
'raw': email
}
});
request.execute(callback);
}
sendMessage('me', Base64.encodeURI(email), function(resp) {
if(resp.labelIds && resp.labelIds.indexOf('SENT') > -1) {
console.log('Your email has been sent.');
}else {
console.log('Something went wrong');
}
});
Upvotes: 1