How to Send email in protractor

we can send email using nodemailer package in protractor

Sending emails is one of the common tasks in real life applications, we send emails when something is failed or when something is complete or just for information sake also we may need to send emails to provides updates to other person.

When we are executing test cases in protractor, you may want to send email to yourself with the status of the execution or sometimes you may need to send the email to the client of the project to keep them updated.

For example, we generate a report in protractor after generating you may want to send it to yourself if the execution is happening through some continuous integration tools like jenkins or Bamboo, because every-time you cannot go there and take the report after the execution.

We will how to send emails in protractor in next topic, to send email we may need extra packages in node.

Protractor doesn't have the capability to send emails but a package called NodeMailer sends email with nodejs. I hope you know that nodejs is pre-requisite to install protractor, so we can use the same package to send emails.

Node mailer

NodeMailer package send emails in node.js but it doesnot come along with protractor or typescript. So we have to install the nodemailer package for sending emails. use below npm command to install nodemailer.


										npm install nodemailer			
										


nodemailer-protractor-send-email What does nodemailer do :
Node mailer will send the mails based on the details we provide to the nodemailer in nodejs, below are things run behind the run of nodemailer.

  • Provide Host details to the Nodemailer
  • Set the user name/email id and password of the mail
  • With above details create a connection with CreateTransport
  • Set the details like how it should show when user open the mail : from (we can make this different from the email id we have provided), replyTo: which mail should be populated when receiver clicks reply, and html, attachments if any
  • send the mail using sendMail method.

Steps to send mail in protractor

Unfortunately, I was not able to send the mail using test block or with typescript, so please do follow below steps to send the email with nodeMailer. Below are the steps to configure nodemailer

Steps to send mail in protractor :

  • First and foremost if you are using gmail, then you should allow low secure apps to send email click this link and allow https://myaccount.google.com/lesssecureapps?pli=1
  • Create a file called sendmail.js
  • Import nodemailer using require statement in javascript
  • 
    var nodemailer = require("nodemailer");			
    
  • We need set details on transport, which would out mail and host, nodemailer automatically populates details for Gmail
  • Set the user name and password from which mail you want to send
  • 
    var transport = nodemailer.createTransport({
    	service: 'Gmail',
        auth: {
            user: "john.doe.ad@gmail.com",
            pass: "MailPassword@123"
        }
    });			
    
  • If you are using other than gmail then you have to set the host and port number like below
  • 
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
    	host: 'smtp.ethereal.email', // host address
    	port: 587,  // mostly same number, rarely changes
    	secure: false, // true for 465, false for other ports
    	auth: {
    		user: "username or email, // generated ethereal user
    		pass: "password" // generated ethereal password
    	}
    });		
    
  • Set Mail Options, like from, to, replyTo, subject, body, attachment
  • We would attach the report that we got from protractor execution
  • 
    var mailOptions = {
        from: 'john.doe.ad@gmail.com', // sender address
        to: 'doe.john.ad@gmail.com', // list of receivers
        subject: 'Report Result', // Subject line
    	//text: info.body,
        text: 'Contains barcode image', // plaintext body
        attachments: [
            {
                'path': 'D:/bar-code.png',
            }]
    };			
    
  • Now call the sendMail method from the transport and provide the mail options as parameter
  • 
    transport.sendMail(mailOptions, function (error, info) {			
    
  • If nodemailer fails to send an mail we will receive the error massage in error parameter otherwise error parameter is set to null
  • If error parameter is null then it executes else block and prints success message otherwise executes if block
  • 
    	if (error) {
            console.log(error);
    		response.send(err);
        } else {
            console.log("Message sent: " + info.response);
    		response.send(info);
        }			
    
  • Unlike other test blocks we cannot execute from the conf file
  • We have to execute the nodemailer from the cmd / terminal
  • In cmd/terminal navigate to folder where sendmail.js is present and execute below node command.
  • 
    											node sendmail.js			
    											

Complete code for sending mail in protractor


var nodemailer = require("nodemailer");
var transport = nodemailer.createTransport({
	service: 'Gmail',
    auth: {
        user: "john.doe.ad@gmail.com",
        pass: "MailPassword@123"
    }
});
var mailOptions = {
    from: 'john.doe.ad@gmail.com', // sender address
    to: 'doe.john.ad@gmail.com', // list of receivers
    subject: 'Reporest Result', // Subject line
	//text: info.body,
    text: 'Contains the test result for the smoke test in html file', // plaintext body
    attachments: [
        {
            'path': 'D:/bar-code.png',
        }]
};
transport.sendMail(mailOptions, function (error, info) {
    if (error) {
        console.log(error);
		response.send(err);
    } else {
        console.log("Message sent: " + info.response);
		response.send(info);
    }
});			


Output of the nodemailer program nodemailer-protractor-typescript

Automate sending mails with Protractor

As I said earlier we cannot write the nodemailer code, even you write it will send any mail or it will not throw anny error.

I can understand your question, then how the hell we automate it ?
just think this, i said we cannot automate nodemailer code because of this we are executing in cmd/terminal. what about automating cmd/terminal command .

I hope you got my point, let's automate the cmd/terminal command for nodemailer.

  • We can use execSync method to run our common line or terminal command, give right path to th mailer javacript file
  • I highly recommend don't use spaces in folder names
  • Print to the console in utf 8 format, so that it would be readable for us
  • 
    import { browser} from 'protractor'
    describe('Protractor Typescript Demo', function() {
    	browser.ignoreSynchronization = true; // for non-angular websites
    	browser.manage().window().maximize()
    	it('Find  Operations', function() {
    		// set implicit time to 30 seconds
    		browser.manage().timeouts().implicitlyWait(30000);
    		
    		browser.get("https://google.com")
    		var execSync = require('child_process').execSync;
    		var cmd = "node ./specs/abcc.js";
    		var options = {
    			encoding: 'utf8'
    		};
    		console.log(execSync(cmd, options));
    	});
    });			
    


    output of automated mail sender with-etf-nodemailer-protractor If you don't use options in output you may see something like this:

    
    browser.get("https://google.com")
    var execSync = require('child_process').execSync;
    var cmd = "node ./specs/abcc.js";
    console.log(execSync(cmd));		
    


    Output in buffer format without-utf

what is nodemailer-smtp-transport

SMTP is the main transport in Nodemailer for delivering messages. SMTP is also the protocol used between different email hosts, so its truly universal.

Almost every email delivery provider supports SMTP based sending, even if they mainly push their API based sending.

We can install nodemailer-smtp-transport package using below npm command, but if you have installed nodemailer with --save option then we don't have to install this as separate package.


									npm install nodemailer-smtp-transport			
									


How to run nodemailer

we cannot run the nodemailer using protractor or using conf file, so we have to run from cmd or from terminal only. use below node command to run nodemailer


									node target-file.js			
									


Errors I Faced

  • NoError : Make sure, You are not running as it block or using some IDE
  • nodemailer.sendmail is not a function : You may face this error, if you trying to run with typescript or if you don't declare the createTransport object

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech