-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
84 lines (72 loc) · 2.48 KB
/
handler.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
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const SES = new AWS.SES();
let {
DESTINATION: destinations,
// eslint-disable-next-line prefer-const
FROM: emailFrom,
// eslint-disable-next-line prefer-const
BUCKET_NAME: bucketName,
} = process.env;
module.exports.processEmails = async (event, context, callback) => {
try {
const mailEvent = event.Records[0].ses;
const { source } = mailEvent.mail;
// Spam filter
if (mailEvent.receipt.spfVerdict.status === 'FAIL'
|| mailEvent.receipt.dkimVerdict.status === 'FAIL'
|| mailEvent.receipt.spamVerdict.status === 'FAIL'
|| mailEvent.receipt.virusVerdict.status === 'FAIL') {
console.log('Dropping spam');
// Stop processing rule set, dropping message
callback(null, { disposition: 'STOP_RULE_SET' });
} else {
const { messageId } = mailEvent.mail;
// If destinations is not an array, we need to make it an arrat
if (!Array.isArray(destinations)) {
destinations = [destinations];
}
// Retrieve email information
const data = await S3.getObject({
Bucket: bucketName,
Key: messageId,
}).promise();
if (!([undefined, null].includes(data.Body))) {
let emailData = data.Body.toString('utf-8');
const realFrom = emailData.match(/^From:.*$/gm);
if (Array.isArray(realFrom) && realFrom.length > 0) {
emailData = emailData.replace(`${realFrom[0]}`, `From: ${emailFrom}`);
}
const returnPath = emailData.match(/^Return-Path:.*$/gm);
if (Array.isArray(returnPath) && returnPath.length > 0) {
emailData = emailData.replace(`${returnPath[0]}`, `Return-Path: ${emailFrom}`);
}
const subject = emailData.match(/^Subject:.*$/gm);
if (Array.isArray(subject) && subject.length > 0) {
emailData = emailData.replace(`${subject[0]}`, `${subject[0]} - ${source}`);
}
try {
await SES.sendRawEmail({
Destinations: destinations,
RawMessage: {
Data: emailData,
},
Source: emailFrom,
}).promise();
} catch (e) {
console.error(e);
}
// Deleting processed Email.
await S3.deleteObject({
Bucket: bucketName,
Key: messageId,
}).promise();
} else {
console.log('No Body');
}
}
callback(null, null);
} catch (error) {
console.error(error.stack || error);
}
};