Created
July 18, 2023 09:45
-
-
Save ByteCrak07/309136d1dd8bfd6a31e1f0ebee732c07 to your computer and use it in GitHub Desktop.
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 { type NextRequest, NextResponse } from 'next/server'; | |
import nodemailer from 'nodemailer'; | |
import Mail from 'nodemailer/lib/mailer'; | |
export async function POST(request: NextRequest) { | |
const { email, name, message } = await request.json(); | |
const transport = nodemailer.createTransport({ | |
service: 'gmail', | |
/* | |
setting service as 'gmail' is same as providing these setings: | |
host: "smtp.gmail.com", | |
port: 465, | |
secure: true | |
If you want to use a different email provider other than gmail, you need to provide these manually. | |
Or you can go use these well known services and their settings at | |
https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json | |
*/ | |
auth: { | |
user: process.env.MY_EMAIL, | |
pass: process.env.MY_PASSWORD, | |
}, | |
}); | |
const mailOptions: Mail.Options = { | |
from: process.env.MY_EMAIL, | |
to: process.env.MY_EMAIL, | |
// cc: email, (uncomment this line if you want to send a copy to the sender) | |
subject: `Message from ${name} (${email})`, | |
text: message, | |
}; | |
const sendMailPromise = () => | |
new Promise<string>((resolve, reject) => { | |
transport.sendMail(mailOptions, function (err) { | |
if (!err) { | |
resolve('Email sent'); | |
} else { | |
reject(err.message); | |
} | |
}); | |
}); | |
try { | |
await sendMailPromise(); | |
return NextResponse.json({ message: 'Email sent' }); | |
} catch (err) { | |
return NextResponse.json({ error: err }, { status: 500 }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment