How to send an existing .pdf (not a blank page) by nodemailer and pdfkit in node

28 Views Asked by At

hello I have a problem because I cannot send a pdf as an attachment via nodemailer. The PDF is sent, but upon receipt it is a blank page. I use node and express.

My function is used to do lead nurturing: I add a lead to my database then I send him my white paper.

const createLead = async (req, res, next) => {
  const myUuid = uuidv4();
  const { date, nameLead, companyLead, emailLead } = req.body;

  try {
    // Create the lead
    const lead = await Lead.create({
      id: myUuid,
      date,
      nameLead,
      companyLead,
      emailLead,
    });

    // Create a new PDF using pdfkit
    const doc = new PDFDocument();
    const pdfPath =
      "uploads/white-paper/livre-blanc-transformation-digitale.pdf";

    // Open the existing PDF file
    const existingPdf = fs.createReadStream(pdfPath);

    // Create a write stream for the new PDF
    const newPdfPath = "uploads/white-paper/new.pdf";
    const newPdf = fs.createWriteStream(newPdfPath);
    doc.pipe(newPdf);

    // Pipe the existing PDF content to the new PDF
    existingPdf.pipe(doc);

    // End the new PDF stream
    doc.end();

    // Configuration nodemailer
    const transporter = nodemailer.createTransport({
      host: process.env.TRANSPORTER_HOST, // Outlook SMTP server
      port: process.env.TRANSPORTER_PORT, // SMTP Port for Outlook
      secureConnection: process.env.TRANSPORTER_SECURE, // false for TLS connections
      service: process.env.TRANSPORTER_SERVICE,
      auth: {
        user: process.env.CONTACT_EMAIL, 
        pass: process.env.CONTACT_PASSWORD, 
      },
      tls: {
        ciphers: "SSLv3",
      },
    });

    // Create an options subject for the email
    const mailOptions = {
      from: process.env.CONTACT_EMAIL,
      to: emailLead,
      subject: "Your white paper on digital transformation",
      text: `
      hi,
      
      ...

      Regards`,
      attachments: [
        {
          filename: "livre-blanc-transformation-digitale.pdf", // Attachment file name
          content: fs.createReadStream(newPdfPath), // Send the newly generated PDF as an attachment
        },
      ],
    };

    // Send the email
    await transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.log("Erreur lors de l'envoi de l'e-mail : " + error);
      } else {
        console.log("E-mail envoyé : " + info.response);
      }
    });

    res.status(201).json({ lead });
  } catch (err) {
    res.status(500).send("Creating lead failed, please try again later.");
    return next();
  }
};

What is needed for the email received to be the same as the one sent from my API ?

Regards,

I'm trying to send a ready-made pdf as an attachment via nodemailer. the email is received but the pdf received is a blank page

0

There are 0 best solutions below