This repository has been archived by the owner on Jan 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail.js
90 lines (89 loc) · 2.7 KB
/
email.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var elide = require('./data/elide')
// Shim the Mailgun send function and export an EventEmitter
// tests can use to check invocations.
/* istanbul ignore else */
if (process.env.NODE_ENV === 'test') {
var EventEmitter = require('events').EventEmitter
var events = new EventEmitter()
module.exports = function (requestLog, message, callback) {
var log = requestLog.child({subsystem: 'email'})
log.info(elide(message, 'docx', 'pdf', 'ics'))
events.emit('message', message)
callback()
}
module.exports.events = events
} else {
var FormData = require('form-data')
var https = require('https')
var pump = require('pump')
var DOCX = require('docx-content-type')
module.exports = function (requestLog, message, callback) {
var domain = process.env.MAILGUN_DOMAIN
var key = process.env.MAILGUN_KEY
var from = process.env.MAILGUN_SENDER + '@' + process.env.MAILGUN_DOMAIN
var log = requestLog.child({subsystem: 'email'})
log.info(elide(message, 'docx', 'pdf', 'ics'))
var form = new FormData()
form.append('from', from)
form.append('to', message.to)
if (message.cc) {
form.append('cc', message.cc)
}
form.append('subject', message.subject)
form.append('o:dkim', 'yes')
form.append('o:require-tls', 'yes')
if (message.text) {
form.append('text', message.text)
}
if (message.html) {
form.append('html', message.html)
}
if (message.docx) {
form.append('attachment', message.docx.data, {
filename: message.docx.name,
contentType: DOCX,
knownLength: message.docx.data.length
})
}
if (message.pdf) {
form.append('attachment', message.pdf.data, {
filename: message.pdf.name,
contentType: 'application/pdf',
knownLength: message.pdf.data.length
})
}
if (message.ics) {
form.append('attachment', message.ics, {
filename: 'expiration.ics',
contentType: 'text/calendar',
knownLength: message.ics.length
})
}
pump(form, https.request({
method: 'POST',
host: 'api.mailgun.net',
path: '/v3/' + domain + '/messages',
auth: 'api:' + key,
headers: form.getHeaders()
}, function (response) {
var status = response.statusCode
if (status === 200) {
log.info({event: 'sent'})
return callback()
}
response
.once('error', function (error) {
log.error(error)
callback(error)
})
.pipe(require('concat-stream')(function (body) {
var error = {
status: response.statusCode,
body: body.toString()
}
log.error(error)
callback(error)
}))
}))
}
}