首页 > 解决方案 > 将使用 jsPDF 生成的 PDF 发送到服务器

问题描述

我正在使用 jsPDF 生成 PDF 客户端。我需要使用 Axios 将它发送到我的 Express 服务器。最后,我需要使用 Nodemailer 通过电子邮件发送。我哪里错了?

客户端代码

//doc creation ....
var res = doc.output('datauristring');   //this line!!!!
axios.post('/mailsender', res).then((res) => {
    if(res.status === 'ok') console.log("Yeah!");
    else console.log(":(");
});

服务器端代码

...

api_router.post('/mailsender', (req, res) => {
    mail.send(req.body, (res) => {
        res.status(200).json({"status": res ? 'ok' : 'error' });
    });
});

mail.js 是

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    host: 'smtp.mail.yahoo.com',
    port: 465,
    secure: true,
    auth: {
        user: 'example@yahoo.it',
        pass: 'password'
    }
});


exports.send = function (data, callback) {
    let mailOptions = {
        from: '"My application" <example@myapp.com>',
        to: "receiverAddress",
        subject: "Attachment experiment",
        text: "My <3",
        attachments: [
            {
                filename: 'attachment.pdf',
                content: data,
                contentType: 'application/pdf',
                encoding: 'base64'    //this line!!!!
            }
        ]
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
            callback(false);
        }
        callback(true);
    });
}

一切正常,除了如果我尝试打开收到的邮件中的附件,预览会说文件已损坏。如果我尝试使用 google chrome 或其他 PDF 阅读器打开它,情况也是如此。可能必须更改带有注释的两行。感谢您的关注!

标签: javascriptreactjsaxiosjspdfnodemailer

解决方案


这很简单:我只需要以这种方式更改附件部分:

attachments: [
    {
        path: data
    }
]

推荐阅读