我创造了一个新的客户,我想给他发一封电子邮件,但这是行不通的。基本上这就是我所做的。我不知道是否应该在这里插入其他代码。
'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'
});
}
};此代码是电子邮件的配置:
'use strict';
var config = require('../config');
var sendgrid = require('sendgrid')(config.sendgridKey);
exports.send = async (to, subject, body) => {
sendgrid.send({
to: to,
from: 'hello@balta.io',
subject: subject,
html: body
});
}PS:我已经尝试过使用sendgrid 2.0.0和上一个版本5.2.3
发布于 2022-02-24 22:29:41
Twilio SendGrid开发人员在这里传道。
首先,您使用的是不推荐的SendGrid npm包。而不是包装,您应该使用套餐。然后,您可以将您的电子邮件服务重写为:
'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: 'hello@balta.io',
subject: subject,
html: body
});
}注意,在本例中,我没有生成send函数async,但返回了调用sendgrid.send的结果,这是一个承诺。
我认为您的代码可能由于其他原因而失败,这就是电子邮件没有发送的原因,但是在您的主代码中没有被捕获到您的try/catch中,因为发送电子邮件是异步的,并且您没有使用等待。因此,修改主块如下:
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'
});
}我将await添加到电子邮件服务函数调用中,并对catch块中的错误进行了一些记录,因此您应该能够看到正在发生的事情。
一定要确保您有验证您正在发送的域或至少核实电子邮件地址。
https://stackoverflow.com/questions/71254668
复制相似问题