emailcypressnodemailertest-reporting

How to send an email with test report in Cypress


I am trying to achieve the following:

  1. Create a simple test report with only names of tests and statuses (Fail/Pass)
  2. Send this report as basic HTML via email.

To achieve that, I need:

  1. A basic reporter instead of the default
  2. Library, which can send an email. I have already tried nodemailer. However, it is not sending any email when I am connecting it with Cypress solution. I have tried different mailbox accounts (nodemailer.createTestAccount(), one from my company, and one from SendGrid), and this is not working (I am not receiving any emails)

Regarding point 2, here is a sample of code I used. This is a code in index.js file - I need to send it after all tests:

after(() => {

var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');

var options = {
  auth: {
    api_user: 'sendgrid_USER',
    api_key: 'sendgrid_APIKEY'
  }
}

var client = nodemailer.createTransport(sgTransport(options));

var email = {
    from: 'FROM_MAIL.PL',
    to: 'TO_MAIL.PL',
  subject: 'Hello',
  text: 'Hello world',
  html: '<b>Hello world</b>'
};

client.sendMail(email, function(err, info){
    if (err ){
      console.log(error);
    }
    else {
      console.log('Message sent: ' + info.response);
    }
});

});


Solution

  • Nodemailer is a module for Node.js, so you will need to run it in a Cypress task.

    Add this to your /cypress/plugins/index.js file

    const sendAnEmail = (message) => {
    
      const nodemailer = require('nodemailer');
      const sgTransport = require('nodemailer-sendgrid-transport');
      const options = {
        auth: {
          api_user: 'sendgrid_USER',
          api_key: 'sendgrid_APIKEY'
        }
      }
      const client = nodemailer.createTransport(sgTransport(options));
    
      const email = {
        from: 'FROM_MAIL.PL',
        to: 'TO_MAIL.PL',
        subject: 'Hello',
        text: message,
        html: '<b>Hello world</b>'
      };
      client.sendMail(email, function(err, info) {
        return err? err.message : 'Message sent: ' + info.response;
      });
    }
    
    module.exports = (on, config) => {
      on('task', {
        sendMail (message) {
          return sendAnEmail(message);
        }
      })
    }
    

    then in the test (or in /cypress/support/index.js for all tests)

    after(() => {
      cy.task('sendMail', 'This will be output to email address')
        .then(result => console.log(result));
    })
    

    This is a basic refactor of the example here, you can adjust things to suit your requirements.