NeahFront9/app/api/mail/send/route.ts

80 lines
1.9 KiB
TypeScript

import { NextResponse } from 'next/server';
import { createTransport } from 'nodemailer';
import { cookies } from 'next/headers';
interface StoredCredentials {
email: string;
password: string;
host: string;
port: number;
}
function getStoredCredentials(): StoredCredentials | null {
const cookieStore = cookies();
const credentialsCookie = cookieStore.get('imap_credentials');
if (!credentialsCookie?.value) {
return null;
}
try {
const credentials = JSON.parse(credentialsCookie.value);
if (!credentials.email || !credentials.password || !credentials.host || !credentials.port) {
return null;
}
return credentials;
} catch (error) {
return null;
}
}
export async function POST(request: Request) {
try {
const credentials = getStoredCredentials();
if (!credentials) {
return NextResponse.json(
{ error: 'No stored credentials found' },
{ status: 401 }
);
}
const { to, cc, bcc, subject, body, attachments } = await request.json();
// Create a transporter using SMTP with the same credentials
const transporter = createTransport({
host: credentials.host,
port: credentials.port,
secure: true, // Use TLS
auth: {
user: credentials.email,
pass: credentials.password,
},
});
// Prepare email options
const mailOptions = {
from: credentials.email,
to,
cc,
bcc,
subject,
text: body,
attachments: attachments?.map((attachment: any) => ({
filename: attachment.name,
content: attachment.content,
encoding: attachment.encoding,
})),
};
// Send the email
await transporter.sendMail(mailOptions);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error sending email:', error);
return NextResponse.json(
{ error: 'Failed to send email' },
{ status: 500 }
);
}
}