2016-04-21 94 views
5

我从我的应用程序向我的用户发送电子邮件通知,但目前我只将它作为文本发送。我想发送它的风格的HTML电子邮件。使用MailGun从Node.JS发送HTML电子邮件

目前我尝试这样:

var data = { 
       from: 'my app', 
       to: user.email, 
       subject: 'Welcome', 
       html: '<div style="width: 500px; height: 400px: background: #ebebeb; color: #ddd"><p>Hi + "user.firstName" + \n ,this email is to inform you that has added their bio to the knowledge Base \n</p></div>' 
      }; 

编译上面的代码不起作用,它不会像我已经把样式 我已经创建了我的本地目录中一个单独的HTML文件。我想发送的每种类型的电子邮件,我希望能够将该HTML文件附加到我的电子邮件。

事情是这样的:

var data = { 
       from: 'my app', 
       to: user.email, 
       subject: 'Welcome', 
       html: welcomeToSiteEmail.html 
      }; 

是上述可能吗?任何帮助将不胜感激。

+0

我也遇到了这个和'mailgun-js'模块不支持很重要'template'属性(我相信这是你想要的,而不是'html'属性) 。我发现这个github项目https://github.com/mailgun/node-prelaunch有一个工作解决方案,它们将nodemailer的模板和mailgun-js传输结合在一起。如果这回答你的问题,我可以拿出专门处理这个问题的代码并创建一个答案。 – skotturi

回答

9

您可以使用mailgun-jsmailcomposer一起发送HTML格式的电子邮件。

mailgun-js docs包括例如:

var domain = 'mydomain.mailgun.org'; 
var mailgun = require('mailgun-js')({ apiKey: "YOUR API KEY", domain: domain }); 
var mailcomposer = require('mailcomposer'); 

var mail = mailcomposer({ 
    from: '[email protected]', 
    to: '[email protected]', 
    subject: 'Test email subject', 
    body: 'Test email text', 
    html: '<b> Test email text </b>' 
}); 

mail.build(function(mailBuildError, message) { 

    var dataToSend = { 
     to: '[email protected]', 
     message: message.toString('ascii') 
    }; 

    mailgun.messages().sendMime(dataToSend, function (sendError, body) { 
     if (sendError) { 
      console.log(sendError); 
      return; 
     } 
    }); 
}); 
+0

为我工作。谢谢! – tanz

4

或者,你可以在故宫退房nodemailer。这是一个很棒的软件包:易于使用和丰富的文档。使用nodemailer,你可以做这样的事情

var nodemailer = require('nodemailer'); 

var transport = nodemailer.createTransport({ 
     host: 'smtp.mailgun.org', 
     port: 587, 
     secure: false, 
     tls: { ciphers: 'SSLv3' }, 
     auth: { 
     user: '<Mailgun SMTP login>', 
     password: 'password' 
     } 
    }); 

transport.sendMail({ 
     from: '<Mailgun SMTP login>', 
     to: ['[email protected]', '[email protected]', /*etc*/], 
     subject: 'Fancy Email', 
     text: 'still send some text to be on the safe side', 
     html: { path: 'path/to/email.html' } 
    }, callback) 
// also returns a promise. 

但是,我会建议你的html电子邮件设计非常全面。编写html电子邮件与网络中的html非常不同。有很多不同的电子邮件客户端会以不同的方式呈现您的html,并且有些Outlook(例如Outlook for Windows和Gmail)不会很好地处理您的html。 Litmus有关于设计html电子邮件的最佳实践的一些很好的资源。

我的建议是将foundation for emails用于您的样式,使用inky来简化编写html电子邮件的语义,并使用inline-css来内联所有样式。即使您使用其他发送邮件的方法,请查看这些资源进行设计。他们会为你节省很多头痛。

-1

类似This

首先,读取文件,并把它作为HTML体。

尝试this