Write Express server to send email

Photo by Greg Rakozy on Unsplash

Write Express server to send email

In this article, I would like to share how to write a Node.js program to send email via Gmail SMTP server, and then deploy it to Google Cloud.


2 min read

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:

  1. Go to your Google Account.
  2. Select Security.
  3. Under "Signing in to Google," turn on 2-Step Verification.
  4. Under "Signing in to Google," select App Passwords.
  5. 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".
  6. Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
  7. Tap Done.

Reference: Sign in with App Passwords

Write Express.js Program

  1. 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"
  2. 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.
  3. Start the program locally for testing.

    npm start
  4. Create a HTML form for testing.

Deploy to Google Cloud

  1. 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".
  2. Create app.yaml for Google Cloud deployment.

    runtime: nodejs14
  3. Enable Cloud Build API. Set the appropriate credential.

  4. Deploy to Google Cloud.
    gcloud app deploy
  5. Change the url value in the javascript in HTML form and test.