95 lines
2.7 KiB
TypeScript
95 lines
2.7 KiB
TypeScript
import nodemailer from 'nodemailer';
|
|
|
|
import base from '../components/mail/base';
|
|
import registration from '../components/mail/registration';
|
|
import reset_password from '../components/mail/reset-password';
|
|
|
|
const config = useRuntimeConfig();
|
|
|
|
export const templates: Record<string, { component: (data: any) => string[], subject: string }> = {
|
|
"registration": { component: registration, subject: 'Bienvenue sur d[any]' },
|
|
"reset-password": { component: reset_password, subject: 'Réinitialisation de votre mot de passe' },
|
|
};
|
|
|
|
import type Mail from 'nodemailer/lib/mailer';
|
|
import type SMTPPool from 'nodemailer/lib/smtp-pool';
|
|
interface MailPayload
|
|
{
|
|
to: string[];
|
|
template: string;
|
|
data: Record<string, any>;
|
|
}
|
|
|
|
const transport = nodemailer.createTransport({
|
|
pool: true,
|
|
host: config.mail.host,
|
|
port: config.mail.port as unknown as number,
|
|
secure: config.mail.port == "465",
|
|
auth: {
|
|
user: config.mail.user,
|
|
pass: config.mail.passwd,
|
|
},
|
|
} as SMTPPool.Options);
|
|
|
|
if(process.env.NODE_ENV === 'production')
|
|
{
|
|
transport.verify((error) => {
|
|
if(error)
|
|
{
|
|
console.log('Mail server cannot be reached');
|
|
console.error(error);
|
|
}
|
|
else
|
|
console.log("Mail server is reachable and ready to communicate");
|
|
});
|
|
}
|
|
|
|
export default defineTask({
|
|
meta: {
|
|
name: 'mail',
|
|
description: ''
|
|
},
|
|
run: async ({ payload, context }) => {
|
|
try {
|
|
if(payload.type !== 'mail')
|
|
{
|
|
throw new Error(`Données inconnues`);
|
|
}
|
|
|
|
const mailPayload = payload.data as MailPayload;
|
|
const template = templates[mailPayload.template];
|
|
|
|
console.log(mailPayload);
|
|
|
|
if(!template)
|
|
{
|
|
throw new Error(`Modèle de mail ${mailPayload.template} inconnu`);
|
|
}
|
|
|
|
const mail: Mail.Options = {
|
|
from: `d[any] - Ne pas répondre <${config.mail.user}>`,
|
|
to: mailPayload.to,
|
|
html: `<html><body>${base(template.component(mailPayload.data))}</body></html>`,
|
|
subject: template.subject,
|
|
textEncoding: 'quoted-printable',
|
|
};
|
|
|
|
if(mail.html === '')
|
|
return { result: false, error: new Error("Invalid content") };
|
|
|
|
const status = await transport.sendMail(mail);
|
|
|
|
if(status.rejected.length > 0)
|
|
{
|
|
return { result: false, error: status.response, details: status.rejectedErrors };
|
|
}
|
|
|
|
return { result: true };
|
|
}
|
|
catch(e)
|
|
{
|
|
console.error(e);
|
|
return { result: false, error: e };
|
|
}
|
|
}
|
|
}) |