1

I'm trying really hard to use mailgun on firebase functions by following this tutorial: https://www.automationfuel.com/firebase-functions-sending-emails/

I wish to be notified by e-mail when something is pushed to a specific node in my real-time database. The code looks so far like this:

const functions = require('firebase-functions')
const mailgun = require('mailgun-js')({
  apiKey: 'key-<######>',
  domain: '<mydomain>.com',
})

exports.sendEmail = functions.database
  .ref('someParent/someChild')
  .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
    }

    const post = event.data.val()
    console.log(post)
    const { email, message } = post

    const data = {
      from: 'mailgun@firebase.com <is this free choice???>',
      subject: 'Hello Word!',
      html: `<p>It's alive!!!</p>`,
      'h:Reply-To': mail,
      to: '<myOwn>@gmail.com',
    }

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

It keeps failing with the following message in the log

Function returned undefined, expected Promise or value

It's not possible to see more than this, which makes it hard to debug..


(I do some transpiling from ES6 before deploying to firebase functions)


Update

I abandoned the concept of sending an email and went for some IoT instead.

But I think that this might work for you (or get you some of the way)

const functions = require('firebase-functions')
const mailgun = require('mailgun-js')({
  apiKey: 'key-<######>',
  domain: '<mydomain>.com',
})

exports.sendEmail = functions.database
  .ref('someParent/someChild')
  .onWrite(event => {
    // Do some checking of data if needed. 

    const post = event.data.val()
    console.log(post)
    const { email, message } = post

    const data = {
      from: 'mailgun@firebase.com <is this free choice???>',
      subject: 'Hello Word!',
      html: `<p>It's alive!!!</p>`,
      'h:Reply-To': mail,
      to: '<myOwn>@gmail.com',
    }

    return mailgun.messages().send(data, (error, body) => {
      console.log(body)
    })
  })
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
  • I'm having this same issue. Did you figure it out> – D34thSt4lker Jan 10 '18 at 06:43
  • I discovered that the if statement was causing problems - so fixed that, but found a much better solution than email - did some IoT instead :-) – Norfeldt Jan 10 '18 at 06:55
  • Can you share what you did? I'm about to code something for a simple web form. I just need to be notified when the data is written. – Rory Jan 19 '18 at 15:38
  • see https://stackoverflow.com/questions/44259405/sending-mailgun-emails-from-cloud-functions-for-firebase-in-an-angular-2-app for more information – Nigel Thorne May 16 '18 at 12:19

0 Answers0