All files / app/api/email route.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42        3x 3x   3x                   3x               3x 1x             3x 2x   2x   1x 1x    
import { NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";
 
export async function POST(req: NextRequest) {
  try {
    const { to, subject, message, attachments } = await req.json();
 
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: Number(process.env.SMTP_PORT),
      secure: false,
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    });
 
    const mailOptions: any = {
      from: `"No Reply" <${process.env.SMTP_USER}>`,
      to,
      subject,
      html: `<p>${message}</p>`,
    };
 
    // If there are attachments, add them to mailOptions
    if (attachments && attachments.length > 0) {
      mailOptions.attachments = attachments.map((file: any) => ({
        filename: file.filename,
        content: file.content.split(";base64,").pop(), // Extract Base64 content
        encoding: "base64",
      }));
    }
 
    const info = await transporter.sendMail(mailOptions);
    console.log("Email sent:", info);
 
    return NextResponse.json({ message: "Message sent successfully!" }, { status: 200 });
  } catch (error) {
    console.error("Email sending error:", error);
    return NextResponse.json({ error: "Error sending message" }, { status: 500 });
  }
}