Sending mailgun emails from Cloud Functions for Fi

2019-02-17 13:40发布

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: "info@xyz.com",
            //The email to contact
        to: "xyz@yahoo.com",
        //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.

1条回答
看我几分像从前
2楼-- · 2019-02-17 14:30

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: 'app@app.com',
    subject: 'Welcome!',
    html: `<p>Welcome! ${user.name}</p>`,
    'h:Reply-To': 'app@app.com',
    to: email
  }

  mailgun.messages().send(data, function (error, body) {
    console.log(body)
  })
})

Source https://www.automationfuel.com/firebase-functions-sending-emails/

查看更多
登录 后发表回答