This commit is contained in:
53
server/api/send-order.post.ts
Normal file
53
server/api/send-order.post.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { to } = await readBody(event)
|
||||
|
||||
if (!to) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Bad Request: "to" field is required',
|
||||
})
|
||||
}
|
||||
|
||||
const config = useRuntimeConfig(event)
|
||||
|
||||
// Убедимся, что все переменные окружения на месте
|
||||
if (!config.smtpHost || !config.smtpPort || !config.smtpUser || !config.smtpPass) {
|
||||
console.error('SMTP configuration is missing in runtime config.')
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Internal Server Error: SMTP configuration is incomplete.',
|
||||
})
|
||||
}
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: config.smtpHost,
|
||||
port: parseInt(config.smtpPort, 10),
|
||||
secure: parseInt(config.smtpPort, 10) === 465, // true for 465, false for other ports
|
||||
auth: {
|
||||
user: config.smtpUser,
|
||||
pass: config.smtpPass,
|
||||
},
|
||||
})
|
||||
|
||||
const mailOptions = {
|
||||
from: `"Vino Galante" <${config.smtpUser}>`,
|
||||
to: to, // Отправляем на email, полученный от клиента
|
||||
bcc: config.smtpUser, // Отправляем скрытую копию самому себе для сохранения в "Отправленных"
|
||||
subject: 'Ваш заказ принят!',
|
||||
text: 'Спасибо за ваш заказ! Мы скоро свяжемся с вами для уточнения деталей.',
|
||||
html: '<b>Спасибо за ваш заказ!</b><p>Мы скоро свяжемся с вами для уточнения деталей.</p>',
|
||||
}
|
||||
|
||||
try {
|
||||
await transporter.sendMail(mailOptions)
|
||||
return { success: true, message: 'Email sent' }
|
||||
} catch (error) {
|
||||
console.error('Error sending email:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: `Failed to send email: ${(error as Error).message || 'Unknown error'}`,
|
||||
})
|
||||
}
|
||||
})
|
Reference in New Issue
Block a user