如何在节点中通过 nodemailer 和 pdfkit 发送现有的 .pdf(不是空白页)

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

提问人:Nicolas M. 提问时间:10/31/2023 更新时间:10/31/2023 访问量:6

问:

您好,我有一个问题,因为我无法通过 nodemailer 将 pdf 作为附件发送。PDF 已发送,但收到后是空白页。我使用 node 和 express。

我的职能是用来培养潜在客户的:我将一个潜在客户添加到我的数据库中,然后我向他发送我的白皮书。

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();
  }
};

收到的电子邮件需要什么才能与从我的 API 发送的电子邮件相同?

问候

我正在尝试通过 nodemailer 将现成的 pdf 作为附件发送。已收到电子邮件,但收到的 PDF 是空白页

节点.js 节点邮件 节点-pdfkit

评论


答: 暂无答案