0

I have this code in a cloud function where I want to use nodemailer to send some notification emails.

const transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: 'mygmailaddress@gmail.com',
        pass: 'apppassword'
    }
})

/* Send email for custom programs to unsigned patients */
exports.sendEmailToNewPatient = functions.https.onRequest( (req, res) => { 
    cors( req, res, () => {
    
        const mailOptions = {
            to:  req.body.userEmail,
            from: 'mygmailaddress@gmail.com',
            subject: `${req.body.doctorName} test!`,
            text: 'Test message',
            html: '<h1>Test message/h1>'
        }

        transporter.sendMail(mailOptions, (error, info) => {
            if( error ) {
                res.send(error.message)
            }
            const sendMailResponse = {
                accepted: info.accepted,
                rejected: info.rejected,
                pending: info.pending,
                envelope: info.envelope,
                messageId: info.messageId,
                response: info.response,
            }
            res.send(sendMailResponse)
        })
    })
})

I'm calling the function using a POST request made with axios, when the request is send I will get a status code of 200 and in the data object of axios response I will have this informations

data:
 code: "EENVELOPE"
 command: "API"

When I check my test email address to verify if the email is sent, I will not have any message as expected.

Any suggestion about?

user9741470
  • 169
  • 12
  • 1
    Did you check spam ? – Pawan Sharma Jun 20 '22 at 12:53
  • @PawanSharma yes, but there is no email. I think the problem is with the post request. I've discovered that the field `to` is missing but not sure why this occur! – user9741470 Jun 20 '22 at 13:01
  • 1
    In that case, you'll want to `console.log(req.body.userEmail)` just before using that value. – Frank van Puffelen Jun 20 '22 at 13:10
  • @FrankvanPuffelen I saw from the log that axios will pass a `data` object with the `userEmail` field inside it. Probably I need to remove data object from axios post request and pass the param directly ? – user9741470 Jun 20 '22 at 13:17

1 Answers1

1

I can see a small mistake in your code that the heading tag is not closed in the html message.

For more reference on how to send the mail using node mailer you can follow the below code. As mentioned in the link:

const functions = require("firebase-functions");
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const cors = require("cors")({
  origin: true
});

exports.emailMessage = functions.https.onRequest((req, res) => {
  const { name, email, phone, message } = req.body;
  return cors(req, res, () => {
    var text = `<div>
      <h4>Information</h4>
      <ul>
        <li>
          Name - ${name || ""}
        </li>
        <li>
          Email - ${email || ""}
        </li>
        <li>
          Phone - ${phone || ""}
        </li>
      </ul>
      <h4>Message</h4>
      <p>${message || ""}</p>
    </div>`;
     var sesAccessKey = 'YOURGMAIL@gmail.com';
     var sesSecretKey = 'password';

     var transporter = nodemailer.createTransport(smtpTransport({
      service: 'gmail',
      auth: {
          user: sesAccessKey,
          pass: sesSecretKey
      }
    }));
    const mailOptions = {
      to: "myemail@myemail.com",
      from: "no-reply@myemail.com",
      subject: `${name} sent you a new message`,
      text: text,
      html: text
    };
    
    transporter.sendMail(mailOptions, function(error, info){
     if(error){
        console.log(error.message);
     }
     res.status(200).send({
       message: "success"
     })
    });
  }).catch(() => {
    res.status(500).send("error");
  });
})

;

For more information you can check the blog , thread and documentation where brief explanations including code is provided.

If all above has been followed well then you can check this thread for further details:

  • First of all, you have to enable the settings to allow less secure apps for the gmail account that you are using. Here is the link.
  • Secondly, Allow access for "Display Unlock captcha option" (Allow access to your Google account). Here is the link.

As mentioned by Frank van Puffelen ,here you can process POST data in Node.js using console.log(req.body.userEmail) for reference you can check link.

Divyani Yadav
  • 1,030
  • 4
  • 9
  • 1
    thank you for the help. I've discovered that the problem was with axios request where I was using a data object instead of passing the needed params directly after the url to reach the cloud function :) – user9741470 Jun 21 '22 at 13:18