How to send customize e-mail with Firebase cloud functions - node.js

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.

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

how do i send emails using mail-gun in my express app

i new to mail-gun i'm trying to send an email after successful payment, but each time the payment is cofirmed , i don't get an email
this how i use it
const domain = 'https://app.mailgun.com/app/sending/domains/sandbox18d7fe3d7f4c6baf525.mailgun.org ';
var mailgun = require('mailgun-js')({
apiKey: "MY_APIKEY",
domain: domain
});
this is my email template
stripe.charges
.create(newCharge, function(err, charge) {
// send response
if (err) {
console.error(err);
res.json({ error: err, charge: false });
} else {
var emailTemplate = `Hello ${newCharge.shipping.name}, \n
Amount: ${newCharge.amount} \n
Thank you!`;
// compose email
var emailData = {
from: "no-reply#YOUR-DOMAIN.com",
to: req.body.email,
subject: "Bundle of Sticks Receipt - " + charge.id,
text: emailTemplate
};
// send email to customer
mailgun.messages().send(emailData);
emailData["to"] = "your_support_email#gmail.com";
emailData["subject"] = `New Order: Bundle of Sticks - ${charge.id}`;
// send email to supplier
mailgun.messages().send(emailData);
// send response with charge data
res.json({ error: false, charge: charge });
}
})
how can i go about this , the payment is always successful but the email dont go through
You should install nodemailer and nodemailer-mailgun-transport and work with those.
And using those it will work a little something like this:
import * as nodemailer from 'nodemailer';
import * as mailGun from 'nodemailer-mailgun-transport';
const auth = {
api_key: <YOUR_API_KEY>
domain: <YOUR_DOMAIN>,
}
const transporter = nodemailer.createTransport(mailGun(auth));
const mailOptions = {
sender: "John Doe",
from: email,
to: '<WHATEVER_EMEIL>',
subject: '<YOUR_SUBJECT>',
text: '<YOUR_TEXT>',
};
transporter.sendMail(mailOptions);
Just edit those to suit your need and variables, but that's generally the approach.

Add various fields in the text section of nodemailer

I'm sending mail from my angular app using nodemailer. I have a variable which has several attributes like firstname, middlename, email, mobile, address. I'm fetching this data from firebase and each variable can be accessed by writing $data.firstname, $data.email. I was able to send only 1 variable right now. I want to send all the variables to the mail with labels
So mail content should be
Email - abc#123
First Name - ABC
Address - LMN
Mobile - 7777777777
Please help me out.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp()
require('dotenv').config()
const {SENDER_EMAIL, SENDER_PASS} = process.env;
exports.sendMailNotification1=functions.firestore.document('submissions/{docID}')
.onCreate((snap, ctx)=> {
const data=snap.data();
let authData=nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure:true,
auth:{
user: SENDER_EMAIL,
pass: SENDER_PASS
}
});
authData.sendMail({
from: 'xxx#gmail.com',
to: 'xyz#gmail.com',
subject: 'Appointment Info ',
text:`${data.fname}`,
html:`${data.email}`,
}).then(res=>console.log('Succesfully Sent')).catch(err=> console.log(err)
);
})
As explained in the NodeMailer doc, you can choose between:
using the message's text element for sending "the plaintext version of the message"
OR
using the message's html element for sending "the HTML version of the message".
So for example, if you use the HTML option you could use an HTML list as follows:
//...
const htmlContent = `<ul><li>Email - ${data.email}</li><li>Address - ${data.address}</li></ul>`;
return authData.sendMail({
from: 'xxx#gmail.com',
to: 'xyz#gmail.com',
subject: 'Appointment Info',
html: htmlContent
})
.then(res => {
console.log('Succesfully Sent');
return null;
})
.catch(err => {
console.log(err);
return null;
});
Note the addition of several returns in the code, see https://firebase.google.com/docs/functions/terminate-functions for more info on this key aspect.

How to send an e-mail using mailgun/mailchimp/etc in an express/node.js app

I want to send automated e-mails like order brief, sign-in e-mail, confirm e-mail, change password e-mail, etc to clients using mailchimp or mailgun or whatever e-mail delivery server because when I used nodemailer, the clients were receiving the e-mails in their spam inbox and sometimes not receiving at all.
Here's the code I used:
automated_emails.js file:
const nodemailer = require('nodemailer');
const ejs = require('ejs');
const user = 'xxx'
const pass = 'xxx';
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: { user, pass }
});
const emailPasswordChange = (email, uuid) => {
ejs.renderFile("./mail/forgot-password.ejs", { uuid }, (err, data) => {
if (err) return console.log(err)
let mailOptions = {
from: 'xxx',
to: email,
subject: "Forgot My Password",
html: data
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) return console.log(error);
});
})
}
module.exports.emailPasswordChange = emailPasswordChange;
The EJS file is a file that contains the template, and I pass to it the user info like e-mail, name, etc.
They are a bunch of functions I call inside the main index.js file.
How do you suggest me to implement this? Is there a way I can put mailchimp/mailgun/etc's email delivery method inside my nodemailer app?
To prevent moving your email to spam folder be sure that send email (from) is same as userEmail account which used by nodemailer.
I'm using gmail account to send emails using 'nodemailer' and it always success, and here is the code which I use:
const nodemailer = require('nodemailer');
var userEmail = 'yourUserName#gmail.com';
var userPassword = 'yourPassword';
var transporter = nodemailer.createTransport(`smtps://${userEmail}:${userPassword}#smtp.gmail.com`);
// setup e-mail data with unicode symbols
var mailOptions = {
from: userEmail, // sender address
to: 'abc1#hotmail.com, abc2#yahoo.com', // list of receivers
subject: 'Demo-1', // Subject line
text: 'Hello world from Node.js', // plaintext body
html: '<b>Hello world from Node.js</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});

Sending emails using Mailgun with NodeMailer package

A couple of days ago I realized that Google has changed the security of gmail accounts, particularly for the possibility of sending emails from applications. After Googling around for a while I couldn't find a fix for it.
So, I resorted to using Mailgun. I created an account and had it enabled with Business verification. However, I still can't send emails. I keep getting an error about the requested URL not being found.
I am suspecting that since I haven't set up a domain yet, it is not picking the mailgun domain it provided by default. Could someone show me how to test sending emails using Mailgun from NodeMailer indicating the sandbox name provided by mailgun.
thanks in advance
José
var nodemailer = require('nodemailer');
// send mail with password confirmation
var transporter = nodemailer.createTransport( {
service: 'Mailgun',
auth: {
user: 'postmaster#sandboxXXXXXXXXXXXXXXXX.mailgun.org',
pass: 'XXXXXXXXXXXXXXXX'
}
});
var mailOpts = {
from: 'office#yourdomain.com',
to: 'user#gmail.com',
subject: 'test subject',
text : 'test message form mailgun',
html : '<b>test message form mailgun</b>'
};
transporter.sendMail(mailOpts, function (err, response) {
if (err) {
//ret.message = "Mail error.";
} else {
//ret.message = "Mail send.";
}
});
I created the Nodemailer transport for mailgun.
Here it how it works.
You install the package with npm install as you would do with any package, then in an empty file:
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
// This is your API key that you retrieve from www.mailgun.com/cp (free up to 10K monthly emails)
var auth = {
auth: {
api_key: 'key-1234123412341234',
domain: 'sandbox3249234.mailgun.org'
}
}
var nodemailerMailgun = nodemailer.createTransport(mg(auth));
nodemailerMailgun.sendMail({
from: 'myemail#example.com',
to: 'recipient#domain.com', // An array if you have multiple recipients.
subject: 'Hey you, awesome!',
text: 'Mailgun rocks, pow pow!',
}, function (err, info) {
if (err) {
console.log('Error: ' + err);
}
else {
console.log('Response: ' + info);
}
});
Replace your API key with yours and change the details and you're ready to go!
It worked me, when I added the domain also to the auth object (not only the api_key). Like this:
var auth = {
auth: {
api_key: 'key-12319312391',
domain: 'sandbox3249234.mailgun.org'
}
};

Resources