Follow following steps :
- 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 :
- Go to your Google Account.
- Select Security.
- 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:
- 2-Step Verification is not set up for your account.
- 2-Step Verification is only set up for security keys.
- Your account is through work, school, or other organisation.
- You turned on Advanced Protection.
- At the bottom, choose Select app and choose the app you using Select device and choose the device you’re using Generate.
- 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.