@barakuda1

Как решить ошибки при отправке nodemailer на react (toBlob is a not function)?

Здравствуйте. Пытаюсь отправить письмо с генерируемым вложением, как pdf файл, но при отправке возникает ошибка:

toBlob is a not function

Мой код клиентской части:

import React, { useRef, useState } from "react";
import { PDFExport } from "@progress/kendo-react-pdf";

function Send() {
    const pdfExportComponent = useRef(null);
    const [recipientEmail, setRecipientEmail] = useState("");

    const handlePdfExport = () => {
        if (pdfExportComponent.current) {
            const { toBlob } = pdfExportComponent.current;
            toBlob((blob) => {
                const formData = new FormData();
                formData.append("pdf", blob, "document.pdf");
                formData.append("recipientEmail", recipientEmail);

                fetch("/send-email", {
                    method: "POST",
                    body: formData,
                })
                    .then((response) => response.json())
                    .then((data) => {
                        console.log("Email sent:", data);
                    })
                    .catch((error) => {
                        console.error("Error sending email:", error);
                    });
            });
        }
    };

    return (
        <div style={{paddingTop: "120px"}}>
            <form
                onSubmit={(e) => {
                    e.preventDefault();
                    handlePdfExport();
                }}
            >
                <label>
                    Recipient Email:
                    <input
                        type="email"
                        value={recipientEmail}
                        onChange={(e) => setRecipientEmail(e.target.value)}
                    />
                </label>
                <button type="submit" className="button">
                    Generate PDF and Send Email
                </button>
            </form>
            <PDFExport ref={pdfExportComponent}>
                <div>
                    {/* Your content to export */}
                    <p>sssf HER </p>
                </div>
            </PDFExport>
        </div>
    );
}

export default Send;


Мой код бэкенда:

require('dotenv').config();

const PORT = process.env.PORT || 5000;

const express = require("express");
const nodemailer = require("nodemailer");
const multer = require("multer");

const app = express();

app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const upload = multer();

app.post("/send-email", upload.single("pdf"), async (req, res) => {
    const transporter = nodemailer.createTransport({
        service: "smtp.yandex.ru",
        port: 465,
        secure: true,
        auth: {
            user: "моя почта",
            pass: "мой пароль",
        },
    });

    const mailOptions = {
        from: "моя почта",
        to: req.body.recipientEmail,
        subject: "PDF Attachment",
        text: "Please find the attached PDF file.",
        attachments: [{ filename: "document.pdf", content: req.file.buffer }],
    };

    try {
        await transporter.sendMail(mailOptions);
        res.json({ message: "Email sent successfully" });
    } catch (error) {
        console.error("Error sending email:", error);
        res.status(500).json({ message: "Error sending email" });
    }
});


const start = async () => {
    try {
        app.listen(PORT, () => console.log(`Server started on PORT = ${PORT}`))
    } catch (e) {
        console.log(e);
    }
}

start();
  • Вопрос задан
  • 79 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы