如何使用Firebase云功能发送自定义电子邮件

时间:2018-11-17 19:46:43

标签: node.js firebase google-cloud-functions nodemailer postmark

我想使用nodemail和邮戳在使用Firebase云功能创建用户后发送邮件。

我遵循了本教程:Dave Martin的Tutorial link

但是继续出现此错误:

  

发送欢迎电子邮件时出错:{状态: 422,消息:'指定了零个收件人',代码: 300 }

这是我的从云功能发送邮件的代码:

//Mail 
const nodemailer = require('nodemailer')
const postmarkTransport = require('nodemailer-postmark-transport')


// Google Cloud environment variable used:
// firebase functions:config:set postmark.key="API-KEY-HERE"
const postmarkKey = functions.config().postmark.key
const mailTransport = nodemailer.createTransport(postmarkTransport({
auth: {
    apiKey: postmarkKey
}
}))
exports.OnUserCreation = functions.auth.user().onCreate((user) => 
{
console.log("user created: " + user.data.uid);
console.log("user email: " + user.data.email);
sendEmail(user);
})

function sendEmail(user) 
{
// Send welcome email to new users
const mailOptions = 
{
    from: '"test" <test@test.com>',
    to: user.email,
    subject: 'Welcome!',
    html: 'hello'
}
// Process the sending of this email via nodemailer
return mailTransport.sendMail(mailOptions)
    .then(() => console.log('Welcome confirmation email sent'))
    .catch((error) => console.error('There was an error while sending the welcome email:', error))
}

我的postmark.key已经在firebase配置中设置了... API告诉我问题是我用来发送邮件信息的格式。我该如何解决?

更新

我还尝试按照以下方式修改mailOptions,并且仍然是相同的错误:

    const mailOptions = {
        from: 'test@test.com',
        to: user.email,
        subject: 'Welcome!',
        textBody: 'hello'
    }

1 个答案:

答案 0 :(得分:6)

决定仅通过阅读邮戳文档(从这方面来说真的很好)来决定从头开始。

这是从Firebase云功能中的事件发送邮件的非常简单的步骤:

1-下载软件包:

运行:npm install postmark

2-注册以加盖邮戳

注册到PostMark -然后找到您的API密钥。

3-设置Firebase环境配置:

运行:firebase functions:config:set postmark.key="API-KEY-HERE"

要添加的4个index.js代码:

//Mail 
const postmark = require('postmark')
const postmarkKey = functions.config().postmark.key;
const mailerClient = new postmark.ServerClient(postmarkKey);

exports.OnUserCreation = functions.auth.user().onCreate((user) => {
console.log("user created: " + user.data.uid);
console.log("user email: " + user.data.email);
return sendEmail(user);
})

// Send welcome email to new users
function sendEmail(user) {
const mailOptions = {
    "From": "XYZ@YOURDOMAIN.com",
    "To": user.data.email,
    "Subject": "Test",
    "TextBody": "Hello from Postmark!"
}
return mailerClient.sendEmail(mailOptions)
    .then(() => console.log('Welcome confirmation email sent'))
    .catch((error) => console.error('There was an error while sending the welcome email:', error))
}

就是这样。

无需下载nodemailer或使用传输器。