Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email via Gmail API (Javascript)

I'm trying to get a hello world sending a mail via the JS Gmail API. I have authorised correctly (labels can be listed) according to this.

I'm using the following code, running in the browser:

const message =
"From: [email protected]\r\n" + 
"To: [email protected]\r\n" +
"Subject: As basic as it gets\r\n\r\n" +
"This is the plain text body of the message.  Note the blank line between the header information and the body of the message.";


// The body needs to be base64url encoded.
const encodedMessage = btoa(message)

const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

gapi.client.gmail.users.messages.send({
    userId: 'me',
    requestBody: {
        // same response with any of these
        raw: reallyEncodedMessage
        // raw: encodedMessage
        // raw: message
    }
}).then(function () { console.log("done!")});

This gives an HTTP 400 response:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidArgument",
    "message": "'raw' RFC822 payload message string or uploading message via /upload/* URL required"
   }
  ],
  "code": 400,
  "message": "'raw' RFC822 payload message string or uploading message via /upload/* URL required"
 }
}

This is using JS API available at https://apis.google.com/js/api.js. RFC822 example taken from MSDN and elsewhere. Web-safe base64 encoding the RFC822 message as far as I can tell is a the standard with this API. Same error in both Firefox and Chrome.

Where am I going wrong?

like image 462
sennett Avatar asked Sep 20 '25 05:09

sennett


2 Answers

I think that the raw data is correct. So how about this modification?

From :

requestBody: {
    // same response with any of these
    raw: reallyEncodedMessage
    // raw: encodedMessage
    // raw: message
}

To :

resource: { // Modified
    // same response with any of these
    raw: reallyEncodedMessage
    // raw: encodedMessage
    // raw: message
}

If this didn't work, please tell me. I would like to think of other solution.

like image 63
Tanaike Avatar answered Sep 23 '25 11:09

Tanaike


I dont know how to code work but code work by removing the body that are been added to you raw statement.

gapi.client.gmail.users.messages.send({
            userId: 'me',
                // resourse: {
                // same response with any of these
                raw: reallyEncodedMessage
                // raw: encodedMessage
                // raw: message
            // }

I hope you try this because answer by @Tanaike was not working for me

like image 22
Adarsh Patel Avatar answered Sep 23 '25 13:09

Adarsh Patel