https://www.npmjs.com/package/mailgun-js

本文转自:https://www.mailgun.com/blog/how-to-send-transactional-email-in-a-nodejs-app-using-the-mailgun-api

Sending transactional emails nowadays is very important for establishing a healthy customer base. Not only you can get powerful re-engagement based on triggers, actions, and patterns you can also communicate important information and most importantly, automatically between your platform and a customer. It’s highly likely that during your life as a developer you’ll have to send automated transactional emails, if you haven’t already, like:

  • Confirmation emails
  • Password reminders

…and many other kinds of notifications. In this tutorial, we’re going to learn how to send transactional emails using the Mailgun API using a NodeJS helper library.

We will cover different scenarios:

  • Sending a single transactional email
  • Sending a newsletter to an email list
  • Adding email addresses to a list
  • Sending an invoice to a single email address

Getting started

We will assume you have installed and know how to operate within the NodeJS environment. The first need we’re going to do is generate a package.json file in a new directory (/mailgun_nodetut in my case). This file contains details such as the project name and required dependencies.

  1. {
  2. "name": "mailgun-node-tutorial",
  3. "version": "0.0.1",
  4. "private": true,
  5. "scripts": {
  6. "start": "node app.js"
  7. },
  8. "dependencies": {
  9. "express": "4",
  10. "jade": "*",
  11. "mailgun-js":"0.5"
  12. }
  13. }

As you can see, we’re going to use expressjs for our web-app scaffolding, with jade as a templating language and finally a community-contributed library for node by bojand In the same folder where you’ve created the package.json file create two additional folders:

  1. views/
  2. js/

You’re set – now sign in to Mailgun, it’s free if you haven’t done it yet and get your API key (first page in the control panel).

Setup a simple ExpressJS app

Save the code below as app.js in the root directory of your app (where package.json is located)

  1. //We're using the express framework and the mailgun-js wrapper
  2. var express = require('express');
  3. var Mailgun = require('mailgun-js');
  4. //init express
  5. var app = express();
  6. //Your api key, from Mailgun’s Control Panel
  7. var api_key = 'MAILGUN-API-KEY';
  8. //Your domain, from the Mailgun Control Panel
  9. var domain = 'YOUR-DOMAIN.com';
  10. //Your sending email address
  11. var from_who = 'your@email.com';
  12. //Tell express to fetch files from the /js directory
  13. app.use(express.static(__dirname + '/js'));
  14. //We're using the Jade templating language because it's fast and neat
  15. app.set('view engine', 'jade')
  16. //Do something when you're landing on the first page
  17. app.get('/', function(req, res) {
  18. //render the index.jade file - input forms for humans
  19. res.render('index', function(err, html) {
  20. if (err) {
  21. // log any error to the console for debug
  22. console.log(err);
  23. }
  24. else {
  25. //no error, so send the html to the browser
  26. res.send(html)
  27. };
  28. });
  29. });
  30. // Send a message to the specified email address when you navigate to /submit/someaddr@email.com
  31. // The index redirects here
  32. app.get('/submit/:mail', function(req,res) {
  33. //We pass the api_key and domain to the wrapper, or it won't be able to identify + send emails
  34. var mailgun = new Mailgun({apiKey: api_key, domain: domain});
  35. var data = {
  36. //Specify email data
  37. from: from_who,
  38. //The email to contact
  39. to: req.params.mail,
  40. //Subject and text data
  41. subject: 'Hello from Mailgun',
  42. html: '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>'
  43. }
  44. //Invokes the method to send emails given the above data with the helper library
  45. mailgun.messages().send(data, function (err, body) {
  46. //If there is an error, render the error page
  47. if (err) {
  48. res.render('error', { error : err});
  49. console.log("got an error: ", err);
  50. }
  51. //Else we can greet and leave
  52. else {
  53. //Here "submitted.jade" is the view file for this landing page
  54. //We pass the variable "email" from the url parameter in an object rendered by Jade
  55. res.render('submitted', { email : req.params.mail });
  56. console.log(body);
  57. }
  58. });
  59. });
  60. app.get('/validate/:mail', function(req,res) {
  61. var mailgun = new Mailgun({apiKey: api_key, domain: domain});
  62. var members = [
  63. {
  64. address: req.params.mail
  65. }
  66. ];
  67. //For the sake of this tutorial you need to create a mailing list on Mailgun.com/cp/lists and put its address below
  68. mailgun.lists('NAME@MAILINGLIST.COM').members().add({ members: members, subscribed: true }, function (err, body) {
  69. console.log(body);
  70. if (err) {
  71. res.send("Error - check console");
  72. }
  73. else {
  74. res.send("Added to mailing list");
  75. }
  76. });
  77. })
  78. app.get('/invoice/:mail', function(req,res){
  79. //Which file to send? I made an empty invoice.txt file in the root directory
  80. //We required the path module here..to find the full path to attach the file!
  81. var path = require("path");
  82. var fp = path.join(__dirname, 'invoice.txt');
  83. //Settings
  84. var mailgun = new Mailgun({apiKey: api_key, domain: domain});
  85. var data = {
  86. from: from_who,
  87. to: req.params.mail,
  88. subject: 'An invoice from your friendly hackers',
  89. text: 'A fake invoice should be attached, it is just an empty text file after all',
  90. attachment: fp
  91. };
  92. //Sending the email with attachment
  93. mailgun.messages().send(data, function (error, body) {
  94. if (error) {
  95. res.render('error', {error: error});
  96. }
  97. else {
  98. res.send("Attachment is on its way");
  99. console.log("attachment sent", fp);
  100. }
  101. });
  102. })
  103. app.listen(3030);

How it works

This above is a simple express app that will run on your local machine on port 3030. We have defined it to use expressjs and the mailgun-js wrapper. These are pretty well-known libraries that will help us quickly set up a small website that will allow users to trigger the sending of email addresses to their address.

First things first

We’ve defined 4 endpoints.

  1. /
  2. /submit/:mail
  3. /validate/:mail
  4. /invoice/:mail

Where :mail is your valid email address. When navigating to an endpoint, Express will send to the browser a different view. In the background, Express will take the input provided by the browser and process it with the help of the mailgun-js library. In the first case, we will navigate to the root that is localhost:3030/ You can see there’s an input box requesting your email address. By doing this, you send yourself a nice transactional email. This is because expressjs takes your email address from the URL parameter and by using your API key and domain does an API call to the endpoint to send emails. Each endpoint will invoke a different layout, I’ve added the code of basic layouts below, feel free to add and remove stuff from it.

Layouts

Save the code below as index.jade within the /views directory

  1. doctype html
  2. html
  3. head
  4. title Mailgun Transactional demo in NodeJS
  5. body
  6. p Welcome to a Mailgun form
  7. form(id="mgform")
  8. label(for="mail") Email
  9. input(type="text" id="mail" placeholder="Youremail@address.com")
  10. button(value="bulk" onclick="mgform.hid=this.value") Send transactional
  11. button(value="list" onclick="mgform.hid=this.value") Add to list
  12. button(value="inv" onclick="mgform.hid=this.value") Send invoice
  13. script(type="text/javascript" src="main.js")

Save the code below as submitted.jade within the /views directory

  1. doctype html
  2. html
  3. head
  4. title Mailgun Transactional
  5. body
  6. p thanks #{email} !

Save the code below as error.jade within the /views directory

  1. doctype html
  2. html
  3. head
  4. title Mailgun Transactional
  5. body
  6. p Well that's awkward: #{error}

Javascript

This code allows the browser to call a URL from the first form field with your specified email address appended to it. This way we can simply parse the email address from the URL with express’ parametered route syntax. Save the code below as main.js within the /js directory

  1. var vForm = document.getElementById('mgform');
  2. var vInput = document.getElementById('mail');
  3. vForm.onsubmit = function() {
  4. if (this.hid == "bulk") {
  5. location = "/submit/" + encodeURIComponent(vInput.value);
  6. }
  7. if (this.hid == "list") {
  8. location = "/validate/" + encodeURIComponent(vInput.value);
  9. }
  10. if (this.hid == "inv") {
  11. location = "/invoice/" + encodeURIComponent(vInput.value);
  12. }
  13. return false;
  14. }
 

Finally, create an empty invoice.txt file in your root folder. This file will be sent as an attachment. Now run npm install (or sudo npm install in some cases depending on your installation) to download dependencies, including Express. Once that’s done run node app.js Navigate with your browser to localhost:3030 (or 0.0.0.0:3030) And that’s how you get started sending transactional email on demand! In our example, we’ve seen how you can send a transactional email automatically when the user triggers a specific action, in our specific case, submitting the form. There are thousands of applications that you could adapt this scenario to. Sending emails can be used for:

  • Registering an account on a site and Hello message email
  • Resetting a password
  • Confirming purchases or critical actions (deleting an account)
  • Two-factor authentication with multiple email addresses

[转]How To Send Transactional Email In A NodeJS App Using The Mailgun API的更多相关文章

  1. Send an email with format which is stored in a word document

    1. Add a dll reference: Microsoft.Office.Interop.Word.dll 2. Add the following usings using Word = M ...

  2. How to Send an Email Using UTL_SMTP with Authenticated Mail Server. (文档 ID 885522.1)

    APPLIES TO: PL/SQL - Version 9.2.0.1 to 12.1.0.1 [Release 9.2 to 12.1]Information in this document a ...

  3. How to Send an Email Using UTL_SMTP with Authenticated Mail Server

    In this Document   Goal   Solution   References APPLIES TO: PL/SQL - Version 9.2.0.1 to 12.1.0.1 [Re ...

  4. 【译】在Flask中使用Celery

    为了在后台运行任务,我们可以使用线程(或者进程). 使用线程(或者进程)的好处是保持处理逻辑简洁.但是,在需要可扩展的生产环境中,我们也可以考虑使用Celery代替线程.   Celery是什么? C ...

  5. Send email alert from Performance Monitor using PowerShell script (检测windows服务器的cpu 硬盘 服务等性能,发email的方法) -摘自网络

    I have created an alert in Performance Monitor (Windows Server 2008 R2) that should be triggered whe ...

  6. 5 Ways to Send Email From Linux Command Line

    https://tecadmin.net/ways-to-send-email-from-linux-command-line/ We all know the importance of email ...

  7. Sending e-mail

    E-mail functionality uses the Apache Commons Email library under the hood. You can use theplay.libs. ...

  8. 在Salesforce中处理Email的发送

    在Salesforce中可以用自带的 Messaging 的 sendEmail 方法去处理Email的发送 请看如下一段简单代码: public boolean TextFormat {get;se ...

  9. magento email模板设置相关

    magento后台 可以设置各种各样的邮件,当客户注册.下单.修改密码.邀请好友等等一系列行为时,会有相关信息邮件发出. 进入magento后台,System > Transactional E ...

随机推荐

  1. C++输出格式

    C++输出格式 C++中默认输出有效位数是6位,即 则输出: 221.111.11011199967 //6位有效数字,自动截取保存六位1.99967e+006 //六位以上且无法省略显示将会变为指数 ...

  2. 【repost】 JS变量重复声明以及忽略var 声明的问题及其背后的原理

    JS的容错率很高,一些其他语言常见的小错误JS都能大度得包容,比如给一个方法传入超出预计的参数.在声明变量之前使用该变量(变量的声明提升解决了这个问题)等等,这里我们就要解剖一下JS变量重复声明以及当 ...

  3. Ubuntu里Eclipse关联Jdk

    Ubuntu里Eclipse关联Jdk 1.在Eclipse安装目录创建jre 文件. 2.ln  -s  jdk目录/bin  bin 输入上述命令,之后eclipse即可打开.

  4. tarjan算法总结

    部分内容引自https://www.cnblogs.com/stxy-ferryman/p/7779347.html Tarjan算法不是一个算法而是一类算法 1.求取强连通分量 强连通分量————有 ...

  5. 安装Pangolin

    Pangolin是一个用于OpenGL显示/交互以及视频输出的一个轻量级 快速开发库 一:安装必要的库 1.Glew sudo apt-get install libglew-dev 2.Cmake ...

  6. 《Java性能调优》学习笔记(1)

    性能的参考指标 执行时间 -- 从代码开始运行到结束的时间 CPU时间 -- 函数或者线程占用CPU的时间 内存分配 -- 程序在运行时占用内存的情况 磁盘吞吐量 -- 描述IO的使用情况 网络吞吐量 ...

  7. Batch_Size 详解

    Batch_Size(批尺寸)是机器学习中一个重要参数,涉及诸多矛盾,下面逐一展开. 首先,为什么需要有 Batch_Size 这个参数? Batch 的选择,首先决定的是下降的方向.如果数据集比较小 ...

  8. Android 通过onTouchEvent判断是否为双击事件

    通过onTouchEvent判断是否为双击事件,通过前面一次up 跟本次down之间的时间差,并且点击的点的坐标偏移来确定是否为双击事件DOUBLE_TAP_TIMEOUT. boolean isMo ...

  9. node.js使用免费的阿里云ip查询获取ip所在地

    在项目过程中,我们常常需要获取IP的所在地.而这一功能一般都是通过一些数据网站的对外接口来实现,这些接口一般情况下都是付费使用的.在这篇文章中我将记录,基于node.js的阿里云免费IP地址查询接口的 ...

  10. 神经网络架构PYTORCH-前馈神经网络

    首先要熟悉一下怎么使用PyTorch来实现前馈神经网络吧.为了方便理解,我们这里只拿只有一个隐藏层的前馈神经网络来举例: 一个前馈神经网络的源码和注释如下:比较简单,这里就不多介绍了. class N ...