Created
May 2, 2023 13:58
-
-
Save KarthickNcog/35714080e4619ea5e4b27be5e00b6a58 to your computer and use it in GitHub Desktop.
Forward email for Gmail API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { google } from 'googleapis'; | |
| // Initialize the Gmail API client | |
| const gmail = google.gmail({ | |
| version: 'v1', | |
| auth: '<YOUR_AUTHORIZATION_TOKEN>' | |
| }); | |
| // Define the message ID of the email to forward | |
| const messageId = 'MESSAGE_ID_TO_FORWARD'; | |
| // Define the recipient and subject of the forwarded email | |
| const recipient = '[email protected]'; | |
| const subject = 'Fwd: Original email subject'; | |
| // Modify the original message to add the FORWARD label | |
| gmail.users.messages.modify({ | |
| userId: 'me', | |
| id: messageId, | |
| resource: { | |
| addLabelIds: ['FORWARD'] | |
| } | |
| }, (err, res) => { | |
| if (err) { | |
| console.error(err); | |
| return; | |
| } | |
| // Create a new message that includes the original message as an attachment | |
| gmail.users.messages.send({ | |
| userId: 'me', | |
| requestBody: { | |
| to: recipient, | |
| subject: subject, | |
| message: { | |
| raw: Buffer.from(`Content-Type: message/rfc822\n` + | |
| `Content-Disposition: attachment; filename="original.eml"\n` + | |
| `Content-Transfer-Encoding: base64\n\n`).toString('base64') + | |
| `${res.data.raw}` | |
| } | |
| } | |
| }, (err, res) => { | |
| if (err) { | |
| console.error(err); | |
| return; | |
| } | |
| console.log(`Message forwarded to ${recipient} with ID: ${res.data.id}`); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment