Invalid arguments when sending basic email through GMail API

I'm trying to send an email via the Gmail API through a Google Apps Script in Sheets using the example from the Gmail API Documentation, but I'm getting an:

Exception: Invalid number of arguments provided. Expected 2-4 only (line 240, file "Code").

Line 240 is when I call Gmail.Users.Messages.send. This looks to be the most basic email message I can construct. Can someone help me with what I'm missing?

function senDAMail() {

  var bdy =  "From: [email protected]\n\r, To: [email protected]\n\r, Subject: test\n\r\n\r, You first build the message with headers like From and Subject as you mentioned, but you have to encode the message before sending it. There is no way around that.";

  var encodemsg = Utilities.base64EncodeWebSafe(bdy);

  Gmail.Users.Messages.send({
    auth: this.oAuth2Client,
    'userId': '[email protected]',
    'resource': {
      'raw': encodemsg
    }
  });
}

Upvotes: 0

Views: 652

Answers (1)

Tanaike
Tanaike

Reputation: 201378

How about this modification?

Modification points:

  • Please remove , of \n\r, To, \n\r, Subject and \n\r\n\r, YouP.
  • Please replace \n\r to \r\n or only \n.
  • The arguments of Gmail.Users.Messages.send(resource, userId) are resource, userId.
    • In your case, I think that resource and userId are {raw: encodemsg} and "me", respectively.

When above points are reflected to your script, it becomes as follows.

Modified script:

function senDAMail() {
  var bdy =  "From: [email protected]\nTo: [email protected]\nSubject: test\n\nYou first build the message with headers like From and Subject as you mentioned, but you have to encode the message before sending it. There is no way around that.";
  var encodemsg = Utilities.base64EncodeWebSafe(bdy);
  Gmail.Users.Messages.send({raw: encodemsg}, "me");
}

Reference:

If this was not the direct solution of your issue, I apologize.

Upvotes: 3

Related Questions