You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.3 KiB
JavaScript
66 lines
1.3 KiB
JavaScript
const koa = require('koa')
|
|
const koaRouter = require('@koa/router')
|
|
const bodyParser = require('koa-bodyparser')
|
|
const nodemailer = require('nodemailer')
|
|
|
|
const app = new koa()
|
|
app.use(bodyParser())
|
|
|
|
const router = new koaRouter()
|
|
|
|
const {contacts, config} = require('./config.json')
|
|
const transport = nodemailer.createTransport(config)
|
|
transport.verify()
|
|
.then(() => console.log(`Email transport ready`))
|
|
.catch((err) => {
|
|
console.error('Cannot verify email transport');
|
|
console.error(err);
|
|
process.exit(1);
|
|
})
|
|
|
|
router.post('/:id', async (ctx) => {
|
|
const {params: {id}, request, response} = ctx
|
|
if(!contacts[id]){
|
|
response.status = 400
|
|
response.body = {
|
|
error: `Invalid contact id "${id}"`
|
|
}
|
|
return
|
|
}
|
|
|
|
const contact = contacts[id]
|
|
const {name, email, phone, preferredContact, message} = request.body
|
|
|
|
const emailBody =
|
|
`You have received a message via ${contact.site} from ${name}:
|
|
|
|
Contact info:
|
|
- ${email}
|
|
- ${phone}
|
|
|
|
Preferred method of contact:
|
|
- ${preferredContact}
|
|
|
|
Message:
|
|
|
|
> ${message}
|
|
`
|
|
|
|
await transport.sendMail({
|
|
from: config.from || config.auth.user,
|
|
to: contact.address,
|
|
subject: contact.subject,
|
|
text: emailBody
|
|
})
|
|
|
|
ctx.status = 200
|
|
ctx.body = {
|
|
status: 'Message sent'
|
|
}
|
|
})
|
|
|
|
app
|
|
.use(router.routes())
|
|
.use(router.allowedMethods())
|
|
.listen(process.env.PORT || 3000)
|