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
|
import 'dotenv/config';
import * as nodemailer from 'nodemailer';
import { continueRetryUntilValidation } from '$lib/utils';
class MistyMountainsMailer {
constructor(username, password, from, domain, port) {
this.from = from;
this.username = username;
this.password = password;
this.domain = domain;
this.port = port;
this.transporter = nodemailer.createTransport({
host: this.domain,
port: this.port,
auth: {
user: this.username,
pass: this.password
},
requireTLS: true,
tls: {
rejectUnauthorized: true
}
});
}
async sendMail(to, subject, message) {
const mail = {
from: this.from,
subject,
html: message,
to
};
return !!(await continueRetryUntilValidation(async () => {
const { messageId } = await this.transporter.sendMail(mail);
return messageId;
}));
}
}
export async function post({ request }) {
const body = await request.json();
const { HCAPTCHA_SECRET, FORM_TO_EMAIL } = process.env;
const mailer = new MistyMountainsMailer(
process.env.SMTP_USERNAME,
process.env.SMTP_PASSWORD,
process.env.FROM_EMAIL,
process.env.SMTP_SERVER,
Number(process.env.SMTP_PORT)
);
const captchaVerified = await fetch(
`https://hcaptcha.com/siteverify?response=${body.captchaToken}&secret=${HCAPTCHA_SECRET}`,
{
method: 'POST'
}
)
.then((res) => res.json())
.then((json) => json.success)
.catch(() => false);
if (!captchaVerified) {
return {
statusCode: 400,
body: {
error: 'Captcha verification failed'
}
};
}
const text = `<h1>new MMT message</h1>
<p>Name: ${body.name}</p>
<p>Phone Number: ${body.phone || 'Not Given'}</p>
<p>Email: ${body.email}</p>
<hr>
<br>
<p>${body.message}</p>
<br>
<p>brought to you by <a href="https://github.com/Simponic/mistymountains">simponic</a></p>`;
const messageSent = await mailer
.sendMail(FORM_TO_EMAIL, `New Message From ${body.name}`, text)
.then(() => true)
.catch((error) => {
console.error(error);
return false;
});
if (!messageSent) {
return {
statusCode: 500,
body: {
error: 'Message could not be sent'
}
};
}
return {
body: {
success: true
}
};
}
|