Send email using nodemailer node typescript

Standard

Follow following steps :

  1. Install dependancies :

npm install –save nodemailer

npm install @types/node –save
npm install @types/nodemailer –save
npm install @types/nodemailer-direct-transport –save
npm install @types/nodemailer-smtp-transport –save
npm install @types/nodemailer-bluebird –save

2. Create a typescript file say – SendEmail.ts

import * as nodemailer from ‘nodemailer’;

export class SendEmail {

private _transporter: nodemailer.Transporter;

constructor() {

const smtpConfig = {

host: ‘smtp.gmail.com’,

port: 465,

secure: true, // use SSL

auth: {

user: SEND_INVITATION_EMAIL_ID,

pass: SEND_INVITATION_EMAIL_APP_PASS // App password

}

};

this._transporter = nodemailer.createTransport(smtpConfig);

}

async sendMail(emailFrom: string,emailTo: string, subject: string, htmlMessage: string) {

let options = { from: emailFrom, to: emailTo, subject: subject, html: content }

return new Promise<void> ( (resolve: (msg: any) => void, reject: (err: Error) => void) => {

this._transporter.sendMail( options, (error, info) => { if (error) { reject(error); } else {

resolve(`Message Sent ${info.response}`);

}

})

} );

}

3. Call function sendMail from another typescript file as like :

let sendEmail = new SendEmail();

const sendEmailResult = await sendEmail.sendMail( SENDER_EMAIL_ID, RECEIVER_EMAIL_ID, subject, sendingMsg);

4. To create SEND_INVITATION_EMAIL_APP_PASS mentioned above follow following steps :

  1. Go to your Google Account.
  2. Select Security.
  3. Under “Signing in to Google,” select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
    1. 2-Step Verification is not set up for your account.
    2. 2-Step Verification is only set up for security keys.
    3. Your account is through work, school, or other organisation.
    4. You turned on Advanced Protection.
  4. At the bottom, choose Select app and choose the app you using  Select device and choose the device you’re using  Generate.
  5. Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
  6. Tap Done.

Ref. https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=637539142002101586-972788534&rd=1

Leave a comment