In this article, I would like to share how to write a Node.js program to send email via Gmail SMTP server using a Google account, and then deploy the program to Google Cloud.
Table of Contents
Generate App Password
First of all, create App Password to be used in the program. Due to security reason, Google does not allow non Google-app to sign in. It is required to explicitly generate an App Password to use.
In order to generate App Password:
- Go to your Google Account.
- Select Security.
- Under "Signing in to Google," turn on 2-Step Verification.
- Under "Signing in to Google," select App Passwords.
- At the bottom,
- choose "Mail" from "Select app"
- choose "Other (Custom name)" from "Select device" A textbox will then be shown. Enter meaning description like "Send Email from application".
- Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
- Tap Done.
Reference: Sign in with App Passwords
Write Express.js Program
- Create package.json.
{
"name": "contact-form-server",
"description": "This script serves as a server to accept and process request from a Contact Form, and then send to data to a destination email",
"scripts": {
"start": "node contact_form_server.js"
},
"version": "0.0.1",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"nodemailer": "^6.7.1"
}
}
-
Create contact_form_server.js (you can have another js script filename, but make sure to change the script name of the "scripts:start" entry in package.json) as the Node.js script.
- express package is used for running a server.
- nodemailer package is used for sending email.
- cors package is used to allow Cross-Origin Resource Sharing.
Start the program locally for testing.
npm start
- Create a HTML form for testing.
Deploy to Google Cloud
- In Google Cloud Console, create App Engine in standard environment using Node.js. The main advantage of running in Standard Environment is that "Application can scale to 0 instances when there is no traffic. Most cost-effective for applications that have significant periods where they are not serving traffic".
- Create app.yaml for Google Cloud deployment.
runtime: nodejs14
- Enable Cloud Build API. Set the appropriate credential.
- Deploy to Google Cloud.
gcloud app deploy
- Change the url value in the javascript in HTML form and test.
Top comments (0)