I am trying to send emails using Mailgun's api from a firebase cloud function. I have tried implementing a nodejs tutorial for the same in the Cloud Function, but I always get "Error: could not handle the request". Please what am I doing wrong.
Cloud Functions code below:
<pre>
<code>
var functions = require('firebase-functions');
var nodemailer = require('nodemailer');
var auth = {
auth: {
api_key: '###################',
domain: 's###############g'
}
}
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
var nodemailerMailgun = nodemailer.createTransport(auth);
exports.sendEmail = functions.https.onRequest((request, response) =>{
//app.get('/', function(req, res) {
test();
});
function test(){
const mailOptions = {
//Specify email data
from: "[email protected]",
//The email to contact
to: "[email protected]",
//Subject and text data
subject: 'Hello from Mailgun',
text: 'Hello, This is not a plain-text email, I wanted to test some spicy Mailgun sauce in NodeJS! <a href="http://0.0.0.0:3030/validate?' + req.params.mail + '">Click here to add your email address to a mailing list</a>'
};
return smtpTransport.sendMail(mailOptions).then(() => {
console.log("It works");
});
}
</pre>
Thanks for your assistance.
As stated by @GokulKathirvel, only paid accounts will send outbound emails. But I was able to attest the functionality in the functions dashboard. You'll receive the following message when the function is triggered:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
With that out of the way, you should also be able to do that using the node package mailgun-js
.
var functions = require('firebase-functions')
var mailgun = require('mailgun-js')({apiKey, domain})
exports.sendWelcomeEmail = functions.database.ref('users/{uid}').onWrite(event => {
// only trigger for new users [event.data.previous.exists()]
// do not trigger on delete [!event.data.exists()]
if (!event.data.exists() || event.data.previous.exists()) {
return
}
var user = event.data.val()
var {email} = user
var data = {
from: '[email protected]',
subject: 'Welcome!',
html: `<p>Welcome! ${user.name}</p>`,
'h:Reply-To': '[email protected]',
to: email
}
mailgun.messages().send(data, function (error, body) {
console.log(body)
})
})
Source https://www.automationfuel.com/firebase-functions-sending-emails/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With