[转]How To Send Transactional Email In A NodeJS App Using The Mailgun API
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.
- {
- "name": "mailgun-node-tutorial",
- "version": "0.0.1",
- "private": true,
- "scripts": {
- "start": "node app.js"
- },
- "dependencies": {
- "express": "4",
- "jade": "*",
- "mailgun-js":"0.5"
- }
- }
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:
- views/
- 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)
- //We're using the express framework and the mailgun-js wrapper
- var express = require('express');
- var Mailgun = require('mailgun-js');
- //init express
- var app = express();
- //Your api key, from Mailgun’s Control Panel
- var api_key = 'MAILGUN-API-KEY';
- //Your domain, from the Mailgun Control Panel
- var domain = 'YOUR-DOMAIN.com';
- //Your sending email address
- var from_who = 'your@email.com';
- //Tell express to fetch files from the /js directory
- app.use(express.static(__dirname + '/js'));
- //We're using the Jade templating language because it's fast and neat
- app.set('view engine', 'jade')
- //Do something when you're landing on the first page
- app.get('/', function(req, res) {
- //render the index.jade file - input forms for humans
- res.render('index', function(err, html) {
- if (err) {
- // log any error to the console for debug
- console.log(err);
- }
- else {
- //no error, so send the html to the browser
- res.send(html)
- };
- });
- });
- // Send a message to the specified email address when you navigate to /submit/someaddr@email.com
- // The index redirects here
- app.get('/submit/:mail', function(req,res) {
- //We pass the api_key and domain to the wrapper, or it won't be able to identify + send emails
- var mailgun = new Mailgun({apiKey: api_key, domain: domain});
- var data = {
- //Specify email data
- from: from_who,
- //The email to contact
- to: req.params.mail,
- //Subject and text data
- subject: 'Hello from Mailgun',
- 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>'
- }
- //Invokes the method to send emails given the above data with the helper library
- mailgun.messages().send(data, function (err, body) {
- //If there is an error, render the error page
- if (err) {
- res.render('error', { error : err});
- console.log("got an error: ", err);
- }
- //Else we can greet and leave
- else {
- //Here "submitted.jade" is the view file for this landing page
- //We pass the variable "email" from the url parameter in an object rendered by Jade
- res.render('submitted', { email : req.params.mail });
- console.log(body);
- }
- });
- });
- app.get('/validate/:mail', function(req,res) {
- var mailgun = new Mailgun({apiKey: api_key, domain: domain});
- var members = [
- {
- address: req.params.mail
- }
- ];
- //For the sake of this tutorial you need to create a mailing list on Mailgun.com/cp/lists and put its address below
- mailgun.lists('NAME@MAILINGLIST.COM').members().add({ members: members, subscribed: true }, function (err, body) {
- console.log(body);
- if (err) {
- res.send("Error - check console");
- }
- else {
- res.send("Added to mailing list");
- }
- });
- })
- app.get('/invoice/:mail', function(req,res){
- //Which file to send? I made an empty invoice.txt file in the root directory
- //We required the path module here..to find the full path to attach the file!
- var path = require("path");
- var fp = path.join(__dirname, 'invoice.txt');
- //Settings
- var mailgun = new Mailgun({apiKey: api_key, domain: domain});
- var data = {
- from: from_who,
- to: req.params.mail,
- subject: 'An invoice from your friendly hackers',
- text: 'A fake invoice should be attached, it is just an empty text file after all',
- attachment: fp
- };
- //Sending the email with attachment
- mailgun.messages().send(data, function (error, body) {
- if (error) {
- res.render('error', {error: error});
- }
- else {
- res.send("Attachment is on its way");
- console.log("attachment sent", fp);
- }
- });
- })
- 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.
//submit/:mail/validate/:mail/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
- doctype html
- html
- head
- title Mailgun Transactional demo in NodeJS
- body
- p Welcome to a Mailgun form
- form(id="mgform")
- label(for="mail") Email
- input(type="text" id="mail" placeholder="Youremail@address.com")
- button(value="bulk" onclick="mgform.hid=this.value") Send transactional
- button(value="list" onclick="mgform.hid=this.value") Add to list
- button(value="inv" onclick="mgform.hid=this.value") Send invoice
- script(type="text/javascript" src="main.js")
Save the code below as submitted.jade within the /views directory
- doctype html
- html
- head
- title Mailgun Transactional
- body
- p thanks #{email} !
Save the code below as error.jade within the /views directory
- doctype html
- html
- head
- title Mailgun Transactional
- body
- 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
- var vForm = document.getElementById('mgform');
- var vInput = document.getElementById('mail');
- vForm.onsubmit = function() {
- if (this.hid == "bulk") {
- location = "/submit/" + encodeURIComponent(vInput.value);
- }
- if (this.hid == "list") {
- location = "/validate/" + encodeURIComponent(vInput.value);
- }
- if (this.hid == "inv") {
- location = "/invoice/" + encodeURIComponent(vInput.value);
- }
- return false;
- }
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的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- 【译】在Flask中使用Celery
为了在后台运行任务,我们可以使用线程(或者进程). 使用线程(或者进程)的好处是保持处理逻辑简洁.但是,在需要可扩展的生产环境中,我们也可以考虑使用Celery代替线程. Celery是什么? C ...
- 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 ...
- 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 ...
- Sending e-mail
E-mail functionality uses the Apache Commons Email library under the hood. You can use theplay.libs. ...
- 在Salesforce中处理Email的发送
在Salesforce中可以用自带的 Messaging 的 sendEmail 方法去处理Email的发送 请看如下一段简单代码: public boolean TextFormat {get;se ...
- magento email模板设置相关
magento后台 可以设置各种各样的邮件,当客户注册.下单.修改密码.邀请好友等等一系列行为时,会有相关信息邮件发出. 进入magento后台,System > Transactional E ...
随机推荐
- maven + eclipse + tomcat热部署 引自:http://jingpin.jikexueyuan.com/article/23068.html
方案二: 1.修改tomcat的server.xml配置文件,在host结点下添加如下代码 Xml代码 <Context docBase="F:\eclipse_workspace ...
- java holdsLock()方法检测一个线程是否拥有锁
http://blog.csdn.net/w410589502/article/details/54949506 java.lang.Thread中有一个方法叫holdsLock(),它返回true如 ...
- 关于git的reset指令说明-soft、mixed、hard
在开发过程中,git的版本管理越来越普及.在版本管理中,最常用和最重要的是重置提交的版本,恢复后悔做了的事.大家都知道用reset命令.但是有几种形态需要整理共享一下,也方便我自己查阅. 一.首先解析 ...
- JavaScript之DOM创建节点
上几篇文章中我们罗列了一些获取HTML页面DOM对象的方法,当我们获取到了这些对象之后,下一步将对这些对象进行更改,在适当的时候进行对象各属性的修改就形成了我们平时看到的动态效果.具体js中可以修改D ...
- Spring5中的DispatcherServlet初始化
Spring MVC像许多其它Web框架,被设计围绕前端控制器(DispatcherServlet)实际的工作是由可配置的,委托组件执行提供了一种用于请求处理的共享算法.这个模型是灵活的,支持不同的工 ...
- 卷积神经网络CNN的原理(三)---代码解析
卷积神经网络在几个主流的神经网络开源架构上面都有实现,我这里不是想实现一个自己的架构,主要是通过分析一个最简单的卷积神经网络实现代码,来达到进一步的加深理解卷积神经网络的目的. 笔者在github上找 ...
- 涨姿势:Spring Boot 2.x 启动全过程源码分析
目录 SpringApplication 实例 run 方法运行过程 总结 上篇<Spring Boot 2.x 启动全过程源码分析(一)入口类剖析>我们分析了 Spring Boot 入 ...
- python学习的准备工作
1.python安装 1.下载: https://www.python.org/downloads/windows/ 2.安装: 安装很简单,就是下一步,只是在最后要勾选上 Add Python 3. ...
- Golang 对MongoDB的操作简单封装
使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装 初始化 操作没有用户权限的MongoDB var globalS *mgo.Session func init() { s ...
- 网站后台搭建--springboot项目是如何创建的
在创建项目之前先说一下ide的问题,从学习软件开始一直到一个月之前,开发用的IDE都是Eclipse,对,就是这个远古时代的开发工具,在使用过程中虽然总是遇到各种bug,但内心里还是存在着一丝理解的想 ...