如何在mailgun电子邮件模板(Node js)中分配变量?

问题描述 投票:0回答:2

我做了一个谷歌云函数,在其中我发送一封电子邮件,其中包含从其他地方收到的一些变量。我正在使用mailgun.js,并且尝试使用已在mailgun中创建的模板发送电子邮件。问题是我找不到替换模板中占位符变量的方法。

这是代码:

mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))

mailgun docs这样说:

var data = {
  from: 'Excited User <[email protected]>',
  to: '[email protected]',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};

据我所知,不能在任何对象中将“ h:X-Mailgun-Variables”编写为键。

有人知道我需要放在哪里或如何放置它?

我认为应该将其作为标题发送,但[mailgun/mailgun-jshighlycaffeinated/mailgun-js均未指定如何传递标题。

javascript node.js mailgun
2个回答
0
投票

我在NodeJ中做过同样的事情,但是使用Nodemailer所以首先我已经使用EJS渲染了文件并通过将变量发送到文件,然后将相同的文件发送给用户

所以它帮助我在文件中分配了不同的属性,因为我喜欢这里的代码

function generateToken_And_SendMail(user) 
{
   token = jwt.sign(user,process.env.privateKey)
  ejs.renderFile(__dirname + '/verification_email.ejs',{verify_token : `${process.env.localhost_address}/verifyToken?Authorization=Bearer%20${token}`
                                                        ,username : user.Fullname},(error,file)=>
  {
    if(error)
    console.log(error)
    else
    sendmail_Config(file,user.userEmail,'Email Verification')
  })
   return token 
}

0
投票

您可以通过使用键周围的引号将h:X-Mailgun-Variables设置为键。

但是您需要使用括号表示法访问对象内的值。

例如

const foo = {
  "ba ar": "foobar",
  "test" : "test"
}

console.log(foo["ba ar"], foo.test)
// #> foobar test


//doesn't work
console.log(foo."ba ar")

© www.soinside.com 2019 - 2024. All rights reserved.