async await not working if sendgrid failed to sent email - node.js

I have a question.
I am trying to sent the user a email when they have created an account.
But when Sendgrid fails to sent the email the async await function didn't notice that and the code runs further.
This is my email module
const sgMail = require('#sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
module.exports = {
FreshleafVerificationEmail: async(receiver) => {
const msg = {
to: receiver,
from: 'xxxx#xxxx.com',
subject: 'Verifieer uw email adres - FreshLeaf',
text: 'Verifieer uw email adres door te klikken op de onderstaande link'
}
await sgMail
.send(msg)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.log(error)
})
}
}
And this is where the method gets executed
try {
//Save settings and user in the database
await FreshleafVerificationEmail(newUser.email)
await newSetting.save();
const user = await newUser.save();
res.status(201).json({message: 'Er is een nieuwe gebruiker aangemaakt', user: user})
}
catch(error) {
res.status(400).json({message: 'Er is een probleem opgetreden', error: error})
}
Can someone help me with this problem

I agree that the answer by #Matt covers the error situation when Sendgrid does not accept the email. As #O.Jones does suggest, the API would be the way to go. I do not work with this particular library, but Sendgrid should return a uniq ID of the email if it was accepted. That can be used to search for the status of the email via API.
Sendgrid provides multiple statuses:
https://docs.sendgrid.com/ui/analytics-and-reporting/email-activity-feed
You should look for Delivered or in case of Deferred you should wait more.
I assume that this may be a bad news, but Sendgrid copies hear a behavior of any other standard email server. With a simpler interface.

The catch is handling the error condition and allows the code to continue. If you want other error handlers to see the error then it needs to throw again:
FreshleafVerificationEmail: async(receiver) => {
const msg = {
to: receiver,
from: 'xxxx#xxxx.com',
subject: 'Verifieer uw email adres - FreshLeaf',
text: 'Verifieer uw email adres door te klikken op de onderstaande link'
}
try {
const response = await sgMail.send(msg)
console.log('Email sent', response[0].statusCode, response[0].headers)
}
catch (error) {
console.log('Email failed to send', msg, error)
throw error
}
}

Related

how to send the auth verification email using sendgrid in node js?

I am a new person learning Node.js and also building a project at the same time. I want that as soon as the user provides their email, it should be verified first. For that, I am using SendGrid, but I am not understanding the errors that SendGrid is giving. Can someone please provide me with the code for how to verify the email using SendGrid for authentication in node js.
below is the code that I found on google
import mail from "#sendgrid/mail";
export const registerEmail = (to) => {
try {
mail.setApiKey(api_key);
const msg = {
to: to,
from: "no-reply#example.com",
subject: "Authentication Code",
text: `Your authentication code is:`,
};
// send the email
mail
.send(msg)
.then(() => {
console.log(`Authentication code sent to ${to}`);
})
.catch((error) => {
console.error(error);
});
} catch (err) {
console.log("this is the error", err);
}
};
error

twilio isn't sending sms nodejs

I use twilio to send sms after a order is placed, but it isn't sending any sms and also not console logging anything.
Code: npm i twilio
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid, authToken);
exports.createOrder = (req, res) => {
const { orders, status, details } = req.body;
const order = new Order({
orders: orders,
status: status,
details: details,
});
order.save((error, order) => {
if (error) return res.status(400).json(error);
if (order) {
// if (res.status === 201) {
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid));
// }
return res.status(201).json({ order });
}
});
};
LINK TO DOC (where I took the code) : https://www.twilio.com/docs/sms/quickstart/node
Twilio developer evangelist here.
There is likely an issue in sending your message, but the code you have is dropping errors, so you can't see what is going on. Try updating it to this:
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid))
.catch(error => console.error(error));
Once you see what the error is, you will be able to fix it. My guess is that you have either configured your Account Sid and Auth Token incorrectly, or you are using a trial account and trying to send a message to a number you haven't verified yet, or you are trying to send a message to a country that isn't enabled.

AWS Cognito ResendConfirmationCode not emailing code - Node / JS

I am using the AWS Cognito and trying to allow for users to resend the initial registration confirmation email (aka they register, and lose/forget/wait too long on the email verification link). When they register it sends the email no problem. When I use the code below for users that are registered and confirmed it works.
However, if i use below to try to resend that initial email confirmation link for a user that is not confirmed, it returns the right result but the email is never delivered. Can you please help with the right way to resend the initial email confirmation. Thanks!
{
"CodeDeliveryDetails": {
"AttributeName": "email",
"DeliveryMedium": "email",
"Destination": "the email address is here"
}
}
resendConfirmationCode(userName: string): Promise<any> {
return new Promise((resolve, reject) => {
const cognitoUser = this.getUserByUsername(userName);
cognitoUser.resendConfirmationCode((error: any, result: any) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}

Unable to send email using MailGun Node API

When trying to send a simple test message via mailgun using their Node api I don't get any errors, but I also am not receiving emails nor am I seeing any response in the mailgun logs.
Here is the code I am using ...
const mailgun = require('mailgun-js')({
apiKey: 'XXXXXXXXXX',
domain: 'https://api.mailgun.net/v3/XXXXXXXXX'
})
async function sendInvite() {
var email = process.argv[process.argv.length - 1]
const data = {
from: 'support#acme.com',
to: email,
subject: 'Welcome!',
html: '<p>Welcome!</p><p>You are very special!</p>'
}
return new Promise((resolve, reject) => {
mailgun.messages().send(data, (error, body) => {
if (error) {
console.error(error)
reject(error)
return
}
console.log(`Invite sent to ${email}`)
console.log(data)
console.log(body)
resolve();
})
})
}
sendInvite().then(() => console.log('Done')).catch((err) => console.error(err))
I discovered that the problem I had was in the format of the domain I was passing into mailgun.
Before I had the following :
const mailgun = require('mailgun-js')({
apiKey: 'XXXXXXXXXX',
domain: 'https://api.mailgun.net/v3/XXXXXXXXX'
})
The problem is that the value for domain should not include the https://api.mailgun.net/v3/ portion of the URL. Instead it should ONLY have your domain, e.g. mail.mydomain.com
Did you attach your credit card to mailGun account? Or if you just need to test your logic, in your account settings you should confirm any email address, which will get emails from mailgun
https://wordpress.org/support/topic/mailgun-http-api-test-failure-status-free-accounts-are-for-test-purposes-only/

How to send customize e-mail with Firebase cloud functions

I want to send a mail once a user is created with a firebase cloud functions, using nodemail and postmark.
I followed this tutorial : Tutorial link from Dave Martin
But keep getting this error:
There was an error while sending the welcome email: { status: 422, message: 'Zero recipients specified', code: 300 }
Here is my code to send a mail from cloud functions:
//Mail
const nodemailer = require('nodemailer')
const postmarkTransport = require('nodemailer-postmark-transport')
// Google Cloud environment variable used:
// firebase functions:config:set postmark.key="API-KEY-HERE"
const postmarkKey = functions.config().postmark.key
const mailTransport = nodemailer.createTransport(postmarkTransport({
auth: {
apiKey: postmarkKey
}
}))
exports.OnUserCreation = functions.auth.user().onCreate((user) =>
{
console.log("user created: " + user.data.uid);
console.log("user email: " + user.data.email);
sendEmail(user);
})
function sendEmail(user)
{
// Send welcome email to new users
const mailOptions =
{
from: '"test" <test#test.com>',
to: user.email,
subject: 'Welcome!',
html: 'hello'
}
// Process the sending of this email via nodemailer
return mailTransport.sendMail(mailOptions)
.then(() => console.log('Welcome confirmation email sent'))
.catch((error) => console.error('There was an error while sending the welcome email:', error))
}
My postmark.key is already setup in the firebase config... The API tell me the problem is the format I use to send the mail informations.. How could I fix it ?
Update
I also tried to modify the mailOptions as follow and still the same error:
const mailOptions = {
from: 'test#test.com',
to: user.email,
subject: 'Welcome!',
textBody: 'hello'
}
Decided to restart from scratch by following only postmark documentation (wich is really good by the way).
So here are the very simple steps to send mail from events in firebase cloud functions:
1- download packages:
Run: npm install postmark
2- register to postmark
Register to PostMark
- then find your API key.
3- setup firebase environment config:
Run : firebase functions:config:set postmark.key="API-KEY-HERE"
4 index.js code to be added:
//Mail
const postmark = require('postmark')
const postmarkKey = functions.config().postmark.key;
const mailerClient = new postmark.ServerClient(postmarkKey);
exports.OnUserCreation = functions.auth.user().onCreate((user) => {
console.log("user created: " + user.data.uid);
console.log("user email: " + user.data.email);
return sendEmail(user);
})
// Send welcome email to new users
function sendEmail(user) {
const mailOptions = {
"From": "XYZ#YOURDOMAIN.com",
"To": user.data.email,
"Subject": "Test",
"TextBody": "Hello from Postmark!"
}
return mailerClient.sendEmail(mailOptions)
.then(() => console.log('Welcome confirmation email sent'))
.catch((error) => console.error('There was an error while sending the welcome email:', error))
}
That's it.
No need to download nodemailer nor use a transporter.

Resources