Files
pfadi-bussle/helpers/mail.ts
2020-10-07 22:46:13 +02:00

57 lines
1.4 KiB
TypeScript

const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY
const SENDGRID_URL = 'https://api.sendgrid.com/v3/mail/send'
// TODO: move to env
const BOOKING_ADMIN_EMAIL = 'tomru@mail.id0.link'
const FROM_EMAIL = 'pfadibussle@mail.id0.link'
if (!SENDGRID_API_KEY) {
throw new Error('NO SENDGRID_API_KEY set!')
}
if (!SENDGRID_API_KEY) {
throw new Error('NO SENDGRID_API_KEY set!')
}
async function sendMail(data: object) {
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${SENDGRID_API_KEY}`,
},
body: JSON.stringify(data),
}
const response = await fetch(SENDGRID_URL, fetchOptions)
if (!response.ok) {
throw new Error(`Unable to send mail`)
}
}
function getReceivedBookingText(booking: { uuid: string }) {
return `Hallo lieber Admin,
es ging folgende Buchung ein: {getBaseURL()}/booking/${booking.uuid}
MfG`
}
export async function sendReceivedBookingMail(booking: { uuid: string }) {
const data = {
personalizations: [
{
to: [{ email: BOOKING_ADMIN_EMAIL }],
},
],
from: { email: FROM_EMAIL },
subject: `Pfadi Bussle - Buchung ${booking.uuid} eingegangen!`,
content: [{ type: 'text/plain', value: getReceivedBookingText(booking) }],
}
try {
await sendMail(data)
} catch (error) {
console.error(`Failed in sendReceivedBookingMail for ${booking.uuid}`)
}
}