1
1
mirror of https://github.com/theoludwig/theoludwig.git synced 2024-12-08 00:44:30 +01:00
.profile/pages/api/send-email.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-04-18 01:56:23 +02:00
import { NextApiRequest, NextApiResponse } from 'next'
import nodemailer from 'nodemailer'
import validator from 'validator'
const EMAIL_PORT = parseInt(process.env.EMAIL_PORT ?? '465', 10)
const emailTransporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: EMAIL_PORT,
secure: EMAIL_PORT === 465,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD
},
tls: {
rejectUnauthorized: false
}
})
export default async (
request: NextApiRequest,
response: NextApiResponse
2021-04-18 01:56:23 +02:00
): Promise<any> => {
if (request.method !== 'POST') {
return response.redirect('/404')
2021-04-18 01:56:23 +02:00
}
let { name, email, subject, message } = request.body as {
2021-04-18 01:56:23 +02:00
name: string
email: string
subject: string
message: string
}
if (
validator.isEmpty(name) ||
validator.isEmpty(email) ||
validator.isEmpty(subject) ||
validator.isEmpty(message)
) {
return response.status(400).json({ type: 'requiredFields' })
2021-04-18 01:56:23 +02:00
}
if (!validator.isEmail(email)) {
return response.status(400).json({ type: 'invalidEmail' })
2021-04-18 01:56:23 +02:00
}
email = validator.normalizeEmail(email) as string
message = validator.trim(message)
message = validator.escape(message)
subject = validator.trim(subject)
subject = validator.escape(subject)
try {
await emailTransporter.sendMail({
from: '"Divlo" <contact@divlo.fr>',
to: email,
subject: `Contact - ${subject}`,
html: `
<b>Name:</b> ${name} <br/>
<b>Email:</b> ${email} <br/>
<b>Message:</b> ${message}
`
})
return response.status(201).json({ type: 'success' })
2021-04-18 01:56:23 +02:00
} catch {
return response.status(500).json({ type: 'serverError' })
2021-04-18 01:56:23 +02:00
}
}