Iago Mendes
Iago Mendes

Reputation: 5

Email body is sent in a file [Gmail API, Node.js]

I have tried to use the Gmail API Node.js Client, but the email body is sent in a file attachment. Everything else is working properly (from, to, subject, etc.).

The original code of my problem can be seen here, but the following is a simpler example of what I am trying to do:

import {google} from 'googleapis'

const accessToken = 'token created using google OAuth2 from googleapis package' // this is working properly, so I won't include the code here

async function sendMail(subject: string, text: string, to: string, from: string)
{
    const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`
    const messageParts =
    [
        `From: ${from}`,
        `To: ${to}`,
        'Content-Type: text/html charset=utf-8',
        'MIME-Version: 1.0',
        `Subject: ${utf8Subject}`,
        '',
        text,
    ]
  
    const message = messageParts.join('\n')
    const encodedMessage = Buffer.from(message)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '')

  const gmail = google.gmail({version: 'v1', auth: accessToken})

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

sendMail('Some subject', 'Some text', '[email protected]', '[email protected]')

The email received by to has no body, and the text variable somehow turns into a file. When using text/html, this file has the extension .html.

I tried to find some tag like Body: or HTML:, but I could not find any. Looking at the official example, I don't understand what is the problem with my code.

Upvotes: 0

Views: 237

Answers (1)

Tanaike
Tanaike

Reputation: 201553

I think that in your header, ; is required to be used as the separator between Content-Type and charset. I thought that this might be the reason of your issue. When your script is modified, it becomes as follows.

From:

'Content-Type: text/html charset=utf-8',

To:

'Content-Type: text/html; charset=utf-8',

Note:

  • In this answer, it supposes that const gmail = google.gmail({version: 'v1', auth: accessToken}) can be used for sending an email. Please be careful this.

Upvotes: 1

Related Questions