Sending an SMTP Mail using Node JS from AWS EC2

In this article, I explain the Node JS Code to send an email using SMTP (Simple Mail Transport Protocol) on an Amazon EC2 instance.

To begin with, there are two ways of sending an E-Mail from AWS. One of them is using SES (Simple Email Service) and the other one is using SMTP.

However, note that sending emails using SES requires access to the internet. Hence, SES is more suitable to the AWS lambda’s because lambdas have a connection to the internet.

And in my case, the EC2 Virtual Host is isolated from the rest of the world. Basically, it has no complete connectivity to the web, except for the selective endpoints.

Therefore, to send Emails AWS provides these instances with an SMTP endpoint.

In code given below which is self -explanatory, I send an E-Mail using the SMTP endpoint provided for my instance
Also, note that to create an SMTP transport I use a node package named NodeMailer instead of using the aws-sdk

import { SendMailOptions, createTransport } from "nodemailer";
import Mail = require("nodemailer/lib/mailer");


let transporter: Mail = createTransport({
    
    // SMTP Endpoint Host 
    host: process.env.smtp_endpoint_host,                   
    
    // SMTP Endpoint Port
    port: Number(process.env.smtp_endpoint_port),           
    
    secure: false,
    
    auth: {
        // SMTP UserID                
        user: process.env.smtp_user,                       
        
        // SMTP Password
        pass: process.env.smtp_pass                        
    },
    
    tls: {
        rejectUnauthorized: false
    }
})

let params:SendMailOptions = {
    // Sender email address
    from: "sender@example.com",                              

     // Reciever Email Addresses
    to: ["receiver1@example.com","receiver2@server.com"] ,  

    subject: "Email Subject",
    text: "Email Body",

    // Attachments if any
    attachments: [                                          
        {   
            path: 'attachment-path'
        }
    ]
}

transporter.sendMail(params,(err,info)=>{
    if(err){
        console.log("Email sending failed")
        console.log(err)
    }
    else{
        console.log("Status - " + info.status)
        console.log("MessageID - " + info.messageId)
        console.log("Email Sent Successesfully")
    }
})

In case you found this post to be informative or helpful do leave a like on it, this encourages me a lot. Also, if you have any suggestions or any questions feel free to leave a comment below!

0

Leave a Reply