Skip to content

5. Send Email

leonardo Rico edited this page Dec 3, 2017 · 3 revisions

Step 1

install the following npm packages

npm install nodemailer nodemailer-smtp-transport --save

Step 2

Add in src/config/index.js and src/config/production.js

  nodemailer: {
    host: 'hostexample',
    secure: true,
    port: 465,
    auth: {
      user: 'example@gmail.com',
      pass: 'examplePassword'
    }
  }

Step 3

Create a folder called nodemailer in src/lib/, and inside it create an index.js file with the following code:

import * as nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
import config from '../../config';

// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({ service: 'gmail', auth: config.nodemailer.auth });
// const transporter = nodemailer.createTransport(smtpTransport(config.nodemailer));

// function send email
export async function send(message) {
  let r = await transporter.sendMail(message);
  await transporter.close();
  return r;
}

Step 4

Use the function to send email from a controller, example from src/api/exampleSendEmail.js

import { result, error } from 'express-easy-helper';
import { send } from '../../lib/nodemailer';

// Send a email
export function index(req, res) {

  // Options
  let options = {
    from: '"Your-app-name 👻" <example@example.com>', // sender address
    to: `${req.swagger.params.email.value}`, // list of receivers -> example1@gmail.com, example2@gmail.com, ...
    subject: 'Welcome ✔', // Subject line
    text: 'Hello world!', // plain text body
    html: '<h1>Hello World!</h1>' // html body
  };
  // Send
  send(options).then(result(res)).catch(error(res));
}

(Optional)

Create router in swagger src/api/swagger/exampleSendEmail.yaml

/api/email/send:
  x-swagger-router-controller: exampleSendEmail
# index
  get:
    operationId: index
    tags:
      - Examples
    summary: Send a email
    description: Send a email
    parameters:
      - name: email
        description: receiver
        in: query
        required: true
        type: string
    responses:
      200:
        description: Success
      500:
        description: Error
Clone this wiki locally