1

I want to send a mail via the gmail API. I have a function that works so far, but my problem is that I don't know how to change the from address. My mails are always send as the user I authorized the API access with.

So I want my mails sent from from.mail@example.com in the following code:

function sendSampleMail(auth, cb) {
  let gmailClass = google.gmail('v1');

  let emailLines = [];

  emailLines.push('From: from.mail@example.vom');
  emailLines.push('To: to.mail@example.com');
  emailLines.push('Content-type: text/html;charset=iso-8859-1');
  emailLines.push('MIME-Version: 1.0');
  emailLines.push('Subject: this would be the subject');
  emailLines.push('');
  emailLines.push('And this would be the content.<br/>');
  emailLines.push('The body is in HTML so <b>we could even use bold</b>');

  const email = emailLines.join('\r\n').trim();

  let base64EncodedEmail = new Buffer.from(email).toString('base64');
  base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_');

  gmailClass.users.messages.send(
    {
      auth: auth,
      userId: 'me',
      resource: {
        raw: email
      }
    },
    cb
  );
}

I don't know if it's even possible to send with different from-mails via the google API. I could not find any information about that and no solutions.

fveltmann
  • 105
  • 2
  • 7

1 Answers1

3

You can't send emails (or make any request) as a different user from the authenticated user because you don't have any permissions to impersonate it.

If you're a G Suite administrator, you can use a service account [1][2] with domain wide delegation [3], which will grant you access to impersonate any gmail account from your domain. You can create a service account on Cloud Platform after selecting a project, from where you'll be able to download the credentials JSON file. And use the JSON Web Tokens methods [4] to authorize your application using the service account JSON.

[1] https://cloud.google.com/iam/docs/service-accounts

[2] https://cloud.google.com/iam/docs/understanding-service-accounts

[3] https://developers.google.com/admin-sdk/directory/v1/guides/delegation

[4] https://github.com/googleapis/google-auth-library-nodejs#json-web-tokens

Andres Duarte
  • 3,166
  • 1
  • 7
  • 14