feat: API to send test email

This commit is contained in:
bsourisse 2023-01-19 12:54:48 +01:00
parent 1d16c5fa54
commit 4fce2ddaab
3 changed files with 75 additions and 0 deletions

14
package-lock.json generated
View file

@ -13,6 +13,7 @@
"chart.js": "^3.9.1",
"next": "^13.0.5",
"next-auth": "^4.17.0",
"nodemailer": "^6.9.0",
"react": "^18.2.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "^18.2.0",
@ -3446,6 +3447,14 @@
"integrity": "sha512-dFSmB8fFHEH/s81Xi+Y/15DQY6VHW81nXRj86EMSL3lmuTmK1e+aT4wrFCkTbm+gSwkw4KpX+rT/pMM2c1mF+A==",
"peer": true
},
"node_modules/nodemailer": {
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.0.tgz",
"integrity": "sha512-jFaCEGTeT3E/m/5R2MHWiyQH3pSARECRUDM+1hokOYc3lQAAG7ASuy+2jIsYVf+RVa9zePopSQwKNVFH8DKUpA==",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/oauth": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz",
@ -7147,6 +7156,11 @@
"integrity": "sha512-dFSmB8fFHEH/s81Xi+Y/15DQY6VHW81nXRj86EMSL3lmuTmK1e+aT4wrFCkTbm+gSwkw4KpX+rT/pMM2c1mF+A==",
"peer": true
},
"nodemailer": {
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.0.tgz",
"integrity": "sha512-jFaCEGTeT3E/m/5R2MHWiyQH3pSARECRUDM+1hokOYc3lQAAG7ASuy+2jIsYVf+RVa9zePopSQwKNVFH8DKUpA=="
},
"oauth": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz",

View file

@ -14,6 +14,7 @@
"chart.js": "^3.9.1",
"next": "^13.0.5",
"next-auth": "^4.17.0",
"nodemailer": "^6.9.0",
"react": "^18.2.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "^18.2.0",

View file

@ -0,0 +1,60 @@
//Lib
import { promises as fs } from 'fs';
import path from 'path';
import { authOptions } from '../auth/[...nextauth]';
import { unstable_getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
if (req.method == 'POST') {
//Verify that the user is logged in.
const session = await unstable_getServerSession(req, res, authOptions);
if (!session) {
res.status(401).json({ message: 'You must be logged in.' });
return;
}
try {
let nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
port: process.env.MAIL_SMTP_PORT,
host: process.env.MAIL_SMTP_HOST,
auth: {
user: process.env.MAIL_SMTP_LOGIN,
pass: process.env.MAIL_SMTP_PWD,
},
secure: true,
});
const mailData = {
from: process.env.MAIL_SMTP_LOGIN,
to: 'email@test.fr',
subject: `Mail test`,
text: 'Corps de test',
html: `<div>HTML test</div><p>Sent from: test</p>`,
};
transporter.sendMail(mailData, function (err, info) {
if (err) {
console.log(err);
res.status(400).json({
message:
'An error occured while sending the email : ' + err,
});
return;
} else {
console.log(info);
res.status(200).json({
message: 'Mail successfully sent.',
});
return;
}
});
} catch (err) {
console.log(err);
res.status(500).json({
status: 500,
message: 'API error, contact the administrator.',
});
}
}
}