This project allows you to send emails using Gmail's API with OAuth2 authentication. It's designed to be secure and avoid issues with less secure app access or username/password authentication.
- Node.js installed on your system
- A Google Cloud Platform account
- Gmail API enabled in your Google Cloud project
-
Clone this repository:
git clone <repository-url> cd <repository-name>
-
Install dependencies:
npm install
-
Set up Google Cloud Project:
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Gmail API for your project
- Go to "APIs & Services" > "Credentials"
- Create OAuth client ID credentials (choose "Desktop app" as the application type)
- Download the credentials and save them as
client.json
in the project root
-
Set up OAuth2:
- Run the OAuth2 setup script:
node oauth2.js
- Follow the prompts to authorize the application
- This will create a
token.json
file in your project root
- Run the OAuth2 setup script:
-
Create a
recipients.json
file in the project root with the following structure:{ "name": "Your Name", "email": "[email protected]", "subject": "Email Subject ${name}", "body": "Email Body ${name}", "receivers": [ { "name": "Recipient Name", "email": "[email protected]" } ] }
-
Change the EMAIL Variable in mailer.js to Your EMAIL whose access token you have generated.
To send emails, run:
node index.js
The script will read the recipients from recipients.json
and send emails accordingly.
If you encounter authentication errors:
- Ensure your Google Cloud project has the Gmail API enabled
- Check that your OAuth consent screen includes the necessary scopes:
https://www.googleapis.com/auth/gmail.send
https://mail.google.com/
- If issues persist, try regenerating your OAuth credentials and obtaining a new refresh token
- Keep your
client.json
andtoken.json
files secure. Do not share them or commit them to public repositories. - The OAuth2 method is more secure than using your Gmail password or less secure app access.
Feel free to submit issues or pull requests if you have suggestions for improvements or encounter any problems.