Daniel Marín
Daniel Marín

Reputation: 123

send email with gmail api not working

I am trying to send an email, by using the google api in node.js

var sendmsg = function(auth) {

var to = '[email protected]',
    subject = 'Hello World',
    content = 'send a Gmail.'

var email = "To:  "+ to +"\r\n"+
    "Subject: "+subject+"\r\n"+
    content;

 var base64EncodedEmail = new Buffer(email).toString('base64');
 var gmail = google.gmail('v1');
 var request = gmail.users.messages.send({
   'userId': auth,
   'message': {
     'raw': base64EncodedEmail
   }
 }, function (err, result) {
       console.log('result'+result);
 });
};

I took this example from the quick start sample in google's documentation, that reads the labels in my email account(which worked fine). And I just changed the scopes to:

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'];

And created that var = email

var to = '[email protected]',
    subject = 'Hello World',
    content = 'send a Gmail.'

var email = "To:  "+ to +"\r\n"+
    "Subject: "+subject+"\r\n"+
    content;

Then I am just trying to use the gmail.users.messages.send method.. But when running the result is returning the following:

<HTML>
 <HEAD>
   <TITLE>Bad Request</TITLE>
 </HEAD>
 <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
   <H1>Bad Request</H1>
   <H2>Error 400</H2>
 </BODY>
</HTML>

Any idea what I am missing? I think the way I am creating my var 'email' is wrong, but I am not sure how it should be

Upvotes: 2

Views: 2428

Answers (2)

user37309
user37309

Reputation: 634

Instead of constructing the body yourself I'd highly reccomend using Nodemailers system:

const sendMail = async () => {
    const mail = await new MailComposer({
          to: ...,
          from: ...,
          subject: ...,
          html: ...,
        });

    const message = await mail.compile().build();

    const encodedMessage = message
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

    await gmail.users.messages.send({
      userId: 'me',
      requestBody: { raw: encodedMessage },
    });
}

Upvotes: 0

Tholle
Tholle

Reputation: 112787

The value of the userId-field has to be the senders email address (or me for short), the auth-object has to be passed in the auth field, and the message should be passed in the resource-field. Your message lacks a From header and an extra new line before the content to be valid. The message also has to be base64url-encoded:

function sendMessage(auth, from, to, subject, content) {
 // The Gmail API requires url safe Base64 
 // (replace '+' with '-', and '/' with '_')
 var encodedEmail = new Buffer(
   'From: ' + from + '\r\n' +
   'To: ' + to + '\r\n' +
   'Subject: ' + subject + '\r\n\r\n' +

   content 
 ).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');

 var gmail = google.gmail('v1');
 var request = gmail.users.messages.send({
   auth: auth,
   userId: 'me',
   resource: {
     raw: encodedEmail
   }
 }, function (err, result) {
   console.log('result:', result);
 });
};

Upvotes: 1

Related Questions