Sending mailgun emails from Cloud Functions for Firebase in an angular 2 app

倾然丶 夕夏残阳落幕 提交于 2019-11-30 08:43:07

问题


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:


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/



来源:https://stackoverflow.com/questions/44259405/sending-mailgun-emails-from-cloud-functions-for-firebase-in-an-angular-2-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!