Neah/app/api/courrier/send/route.ts
2025-04-24 16:58:21 +02:00

109 lines
3.1 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { prisma } from '@/lib/prisma';
import nodemailer from 'nodemailer';
export async function POST(request: Request) {
try {
console.log('Starting email send process...');
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
console.log('No session found');
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Get credentials from database
console.log('Fetching credentials for user:', session.user.id);
const credentials = await prisma.mailCredentials.findUnique({
where: {
userId: session.user.id
}
});
if (!credentials) {
console.log('No credentials found for user');
return NextResponse.json(
{ error: 'No mail credentials found. Please configure your email account.' },
{ status: 401 }
);
}
// Get the email data from the request
const { to, cc, bcc, subject, body, attachments } = await request.json();
console.log('Email data received:', { to, cc, bcc, subject, attachments: attachments?.length || 0 });
if (!to) {
console.log('No recipient specified');
return NextResponse.json(
{ error: 'Recipient is required' },
{ status: 400 }
);
}
// Create SMTP transporter with Infomaniak SMTP settings
console.log('Creating SMTP transporter...');
const transporter = nodemailer.createTransport({
host: 'smtp.infomaniak.com',
port: 587,
secure: false,
auth: {
user: credentials.email,
pass: credentials.password,
},
tls: {
rejectUnauthorized: false
},
debug: true // Enable debug logging
});
// Verify SMTP connection
console.log('Verifying SMTP connection...');
try {
await transporter.verify();
console.log('SMTP connection verified successfully');
} catch (error) {
console.error('SMTP connection verification failed:', error);
throw error;
}
// Prepare email options
console.log('Preparing email options...');
const mailOptions = {
from: credentials.email,
to: to,
cc: cc || undefined,
bcc: bcc || undefined,
subject: subject || '(No subject)',
html: body,
attachments: attachments?.map((file: any) => ({
filename: file.name,
content: file.content,
contentType: file.type
})) || []
};
// Send the email
console.log('Sending email...');
const info = await transporter.sendMail(mailOptions);
console.log('Email sent successfully:', info.messageId);
return NextResponse.json({
success: true,
messageId: info.messageId
});
} catch (error) {
console.error('Error sending email:', error);
return NextResponse.json(
{
error: 'Failed to send email',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}