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 people.

When we are executing test cases in protractor, you may want to send an 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 the next topic, to send an email we may need extra packages in nodejs.

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

Browser Windows handling in Protractor

Node mailer

NodeMailer package send emails in nodejs, but the package does not 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 emails 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 the above details create a connection with CreateTransport
  • Set the details like how it should show when the user opens the mail like 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 the sendMail method.

Handling Cookies in protractor

Steps to send mail in protractor

Unfortunately, I was not able to send the mail using a test block or with typescript, so please do follow the 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: "[email protected]",
        pass: "[email protected]"
    }
});
    • 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: '[email protected]', // sender address
    to: '[email protected]', // 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 a parameter
transport.sendMail(mailOptions, function (error, info) {
    • If nodemailer fails to send an email we will receive the error message in the error parameter; otherwise, the error parameter is set to null
    • If the 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 the folder where sendmail.js is present and execute below node command.
node sendmail.js

The Complete code for sending mail in protractor

var nodemailer = require("nodemailer");
var transport = nodemailer.createTransport({
	service: 'Gmail',
    auth: {
        user: "[email protected]",
        pass: "[email protected]"
    }
});
var mailOptions = {
    from: '[email protected]', // sender address
    to: '[email protected]', // 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);
    }
});


The Output of the nodemailer program nodemailer-protractor-typescript

Logging in Protractor with Winston

Automate sending emails with Protractor

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

I can understand your question, then how the hell we automate it ?
Just think this, I said we could not 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 the mailer javascript 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));
	});
});


the output of automated mail sender with-etf-nodemailer-protractor If you don't use options in the 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

CSV Files with Protractor

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 it's 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 a separate package.

npm install nodemailer-smtp-transport

How to run nodemailer

We cannot run the nodemailer using the 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 are trying to run with typescript or if you don't declare the createTransport object

Protractor Interview Questions

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • priyadarsini
    I'm receiving the below error while using the above code
    ? Cucumber HTML report E:MSTWebsite
    eportshtml/report.html generated successfully ?
    Error: Greeting never received
        at SMTPConnection._formatError (E:MSTWebsite
    ode_modules
    odemailerlibsmtp-connectionindex.js:784:19)
        at SMTPConnection._onError (E:MSTWebsite
    ode_modules
    odemailerlibsmtp-connectionindex.js:770:20)
        at Timeout.<anonymous> (E:MSTWebsite
    ode_modules
    odemailerlibsmtp-connectionindex.js:704:22)
        at listOnTimeout (internal/timers.js:531:17)
        at processTimers (internal/timers.js:475:7) {
      code: 'ETIMEDOUT',
      command: 'CONN'
    }
    [13:54:26] E/launcher - BUG: launcher exited with 1 tasks remaining
    npm ERR! Test failed.  See above for more details.
    Reply