-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmailServer.js
190 lines (168 loc) · 5.74 KB
/
EmailServer.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const {
SQSClient,
ReceiveMessageCommand,
DeleteMessageCommand,
} = require("@aws-sdk/client-sqs");
const aws = require("aws-sdk");
const dotenv = require("dotenv");
const fs = require("fs");
const path = require("path");
const Handlebars = require("handlebars");
dotenv.config();
// Update AWS credentials and region for aws-sdk
aws.config.update({
endpoint: process.env.AWS_ENDPOINT_SES,
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
// Initialize SES using aws-sdk
const ses = new aws.SES();
const sqsClient = new SQSClient({
endpoint: process.env.AWS_ENDPOINT_SQS,
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
const email_queue = process.env.EMAIL_SERVICE_SQS;
// Function to verify the email address before sending the email
async function verifyEmail(email) {
try {
const params = {
EmailAddress: email,
};
const response = await ses.verifyEmailAddress(params).promise();
console.log("Email verification initiated:", response);
} catch (error) {
console.error("Error verifying email:", error);
}
}
// Function to load and compile Handlebars template
function loadTemplate(templateName) {
const templatePath = path.join(__dirname, 'templates', `${templateName}.hbs`);
const templateContent = fs.readFileSync(templatePath, 'utf-8');
return Handlebars.compile(templateContent);
}
// Function to send the email using aws-sdk SES
async function sendEmail(emailData) {
const template = loadTemplate(emailData.templateName);
const htmlContent = template(emailData.templateData);
const input = {
"Destination": {
"ToAddresses": emailData.To,
},
"Message": {
"Body": {
"Html": {
"Data": htmlContent,
}
},
"Subject": {
"Data": emailData.subject,
}
},
"Source": process.env.SENDER_EMAIL,
};
try {
const response = await ses.sendEmail(input).promise();
console.log("Email sent successfully:", response.MessageId);
} catch (error) {
console.error("Error sending email:", error);
}
}
async function receiveAndProcessSQSMessage(queue_url) {
try {
const receiveMessageCommand = new ReceiveMessageCommand({
QueueUrl: queue_url,
MaxNumberOfMessages: 1,
});
const data = await sqsClient.send(receiveMessageCommand);
if (data.Messages && data.Messages.length > 0) {
const message = data.Messages[0];
console.log("Received message:", message.Body);
const response = JSON.parse(message.Body);
// First verify the email address
await verifyEmail(process.env.SENDER_EMAIL);
const emailData = parseMessage(response);
// Then send the email
await sendEmail(emailData);
// Delete the message from SQS after processing
const deleteMessageCommand = new DeleteMessageCommand({
QueueUrl: queue_url,
ReceiptHandle: message.ReceiptHandle,
});
await sqsClient.send(deleteMessageCommand);
console.log("Message deleted from SQS.");
}
} catch (error) {
console.error("Error receiving or processing message from SQS:", error);
}
}
function parseMessage(response) {
let subject, templateName, templateData;
const To = response.emails;
switch (response.type) {
case "new-service-request":
subject = "New Service Request Posted";
templateName = "new-service-request";
templateData = {
username: response.data.username,
serviceTitle: response.data.serviceTitle,
viewServiceLink: `${process.env.WEBSITE_URL}/services/${response.data.serviceId}`
};
break;
case "service-request-approved":
subject = "Your Service Request Has Been Approved!";
templateName = "service-request-approved";
templateData = {
username: response.data.username,
serviceTitle: response.data.serviceTitle,
viewServiceLink: `${process.env.WEBSITE_URL}/services/${response.data.serviceId}`
};
break;
case "service-request-completed":
subject = "Service Request Completed - Time to Withdraw Your Earnings!";
templateName = "service-request-completed";
templateData = {
username: response.data.username,
serviceTitle: response.data.serviceTitle,
viewServiceLink: `${process.env.WEBSITE_URL}/services/${response.data.serviceId}`
};
break;
case "service-request-rejected":
subject = "Service Request Rejected";
templateName = "service-request-rejected";
templateData = {
username: response.data.username,
serviceTitle: response.data.serviceTitle,
viewServiceLink: `${process.env.WEBSITE_URL}/services/${response.data.serviceId}`
};
break;
case "new-comment-on-service":
subject = "New Comment on Your Service";
templateName = "new-comment-on-service";
templateData = {
username: response.data.username,
serviceTitle: response.data.serviceTitle,
viewServiceLink: `${process.env.WEBSITE_URL}/services/${response.data.serviceId}`
};
break;
default:
throw new Error("Unknown message type");
}
console.log("---------------Email parsed-------------");
console.log("Subject:", subject);
console.log("To:", To);
console.log("Template Name:", templateName);
console.log("Template Data:", templateData);
console.log("-----------------------------------------");
return { subject, To, templateName, templateData };
}
function pollMessages() {
setInterval(() => {
receiveAndProcessSQSMessage(email_queue);
}, 5000);
}
pollMessages();