Created
October 10, 2023 02:12
-
-
Save bdlowery/12f72179a8a12cedf925c1d55acca243 to your computer and use it in GitHub Desktop.
postmark.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextResponse } from "next/server"; | |
import { ServerClient } from "postmark"; | |
const { POSTMARK_API, TURNSTILE_SECRET } = process.env; | |
const client = new ServerClient(POSTMARK_API); | |
export async function POST(req) { | |
const body = await req.json(); | |
const { form, token } = body; | |
let images = ``; | |
const valid = await validateTurnstile(req, token); | |
form.images.forEach((image) => { | |
images += ` | |
<div style="margin-bottom: 10px;"><img src="https://ucarecdn.com/${image}/-/format/jpeg/-/resize/600x/" /></div> | |
`; | |
}); | |
let emailBody = ` | |
<h2>New Lead:<h2> | |
<h3>${form.location.toUpperCase()}</h3> | |
<br> | |
<div><strong>First Name</strong>: ${form.firstName}</div> | |
<div><strong>Last Name</strong>: ${form.lastName}</div> | |
<div><strong>Email</strong>: ${form.email}</div> | |
<div><strong>Phone</strong>: ${form.phone}</div> | |
<br> | |
<div><strong>Message</strong>: ${form.notes}</div> | |
<br><br> | |
${form.images.length > 0 ? "<h4>Images</h4>" : ""} | |
${images} | |
`; | |
const emailTo = valid ? "[email protected]" : "[email protected]"; | |
await client.sendEmailWithTemplate({ | |
TemplateId: "29582501", | |
TemplateModel: { | |
product_url: "https://unwrapdesign.com/", | |
product_name: "Unwrap Dashboard", | |
company_name: "Unwrap Design", | |
company_address: "", | |
body: emailBody, | |
}, | |
InlineCss: true, | |
From: `Unwrap Design [email protected]`, | |
To: emailTo, | |
ReplyTo: form.email, | |
TrackOpens: true, | |
Tag: `all-phase-plumbing-next`, | |
MessageStream: "outbound", | |
}); | |
setTimeout(() => { | |
return NextResponse.json({ status: "success" }); | |
}, 1000); | |
} | |
async function validateTurnstile(req, token) { | |
const ip = req.headers["x-forwarded-for"]; | |
// Validate the token by calling the | |
// "/siteverify" API endpoint. | |
let formData = new FormData(); | |
formData.append("secret", TURNSTILE_SECRET); | |
formData.append("response", token); | |
formData.append("remoteip", ip); | |
const url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; | |
const result = await fetch(url, { | |
body: formData, | |
method: "POST", | |
}); | |
const outcome = await result.json(); | |
if (outcome.success) { | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment