How can I send an email to a person using Cloud Functions and Nodemailer? On my app there's a contact screen where users can ask questions and send feedback to the app, and when the user presses a button, the Cloud Function gets triggered. However, I don't seem to recieve any emails whatsoever, I even checked the "Spam" folder. What am I doing wrong?
My code for the Cloud Function looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp(functions.config().firebase);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'exampleemailpassword'
}
});
exports.sendEmail = functions.https.onRequest((request, response) => {
const { sender, phone, message } = request.query;
const mailOptions = {
from: sender.toLowerCase(),
to: '[email protected]',
subject: 'New feedback email',
text: `${message} Phone: ${phone}`
};
// eslint-disable-next-line consistent-return
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
response.send(err.toString());
}
response.send('Email sent');
});
});
CodePudding user response:
I see what you are doing wrong, you can't use gmail's SMTP transport service in server environments other than your own computer
Gmail has a limit of 500 recipients a day (a message with one To and one Cc address counts as two messages since it has two recipients) for @gmail.com addresses and 2000 for Google Apps customers, larger SMTP providers usually offer about 200-300 recipients a day for free.
So I would recommend you to use a service like EmailJS to send emails
CodePudding user response:
I was doing it wrong, I had to return a code to the HttpRequest in order to run the function property. Then, it works
exports.sendEmail = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const { sender, phone, message } = request.query;
const mailOptions = {
from: sender.toLowerCase(),
to: '[email protected]',
subject: 'New feedback email',
text: `${message} \nEmail: ${sender.toLowerCase()}\nPhone: ${phone}`
};
return transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return response.status(500).send({
data: {
status: 500,
message: error.toString()
}
});
}
return response.status(200).send({
data: {
status: 200,
message: 'sent'
}
});
});
});
});