Pedro Abritta
Pedro Abritta

Reputation: 31

Send email using sendgrid - Node

I created a new customer and I want to send an email to him but it's not working. This is basically what I did. I don't know if I should insert here any code else.

'use strict';

const ValidationContract = require('../validators/fluent-validator')
const repository = require('../repositories/customer-repository');
const md5 = require('md5');
const config = require('../config');
const emailService = require('../services/email-services');

exports.post = async (req, res, next) => {
    let contract = new ValidationContract();
    contract.hasMinLen(req.body.name, 3, 'O nome deve ter no mínimo 3 caracteres');
    contract.isEmail(req.body.email, 'Email inválido');
    contract.hasMinLen(req.body.password, 8, 'A senha deve ter no mínimo 8 caracteres');

    //se for inválido: 
    if (!contract.isValid()) {
        res.status(400).send(contract.errors()).end();
        return;
    }

    try {
        await repository.create({
            name: req.body.name,
            email: req.body.email,
            password: md5(req.body.password + global.SALT_KEY)
        });

        emailService.send(
            req.body.email,
            'Bem vindo ao Blastoff - TooDoo',
            global.EMAIL_TMPL.replace('{0}', req.body.name
        ));

        res.status(201).send({
            message: 'Cliente cadastrado com sucesso'
        });
    } catch (e) {
        res.status(500).send({
            message: 'Falha ao processar requisição'
        });
    }
};

This code is the email's config:

'use strict';

var config = require('../config');
var sendgrid = require('sendgrid')(config.sendgridKey);

exports.send = async (to, subject, body) => {
    sendgrid.send({
        to: to,
        from: '[email protected]',
        subject: subject,
        html: body
    }); 
}

PS: I already tried using sendgrid 2.0.0 and the last version 5.2.3

Upvotes: 0

Views: 82

Answers (1)

philnash
philnash

Reputation: 73075

Twilio SendGrid developer evangelist here.

First, you are using a deprecated SendGrid npm package. Instead of the sendgrid packagage you should use the @sendgrid/mail package. You can then rewrite your email service to:

'use strict';

const config = require("../config");
const sendgrid = require("@sendgrid/mail");
sendgrid.setApiKey(config.sendgridKey);

exports.send = (to, subject, body) => {
  return sendgrid.send({
    to: to,
    from: '[email protected]',
    subject: subject,
    html: body
  });
}

Note, in this case I did not make the send function async, but I did return the result of calling sendgrid.send which is a promise.

I think that your code is likely failing for some other reason, which is why the email isn't sent, but that wasn't getting caught in your try/catch in your main code because sending the email was asynchronous and you did not use await. So, alter the main block to look like this:

    try {
        await repository.create({
            name: req.body.name,
            email: req.body.email,
            password: md5(req.body.password + global.SALT_KEY)
        });

        await emailService.send(
            req.body.email,
            'Bem vindo ao Blastoff - TooDoo',
            global.EMAIL_TMPL.replace('{0}', req.body.name
        ));

        res.status(201).send({
            message: 'Cliente cadastrado com sucesso'
        });
    } catch (e) {
        console.error(e);
        if (e.response) {
            console.error(e.response.body);
        }
        res.status(500).send({
            message: 'Falha ao processar requisição'
        });
    }

I added await to the email service function call and some logging of the error in your catch block so you should be able to see what is going on.

Do ensure that you have authenticated the domain you are sending from or verified the email address at the least.

Upvotes: 1

Related Questions