Nodemailer图像附件没有数据 [英] Nodemailer Image Attachment Has No Data

查看:163
本文介绍了Nodemailer图像附件没有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送图像附件和它的未来通过,但没有数据。 0KB大小。这就是使用这种code:

  VAR路径=要求('路径');
VAR uploadDir = path.dirname(require.main.filename);
//这实际上产生了开始于我的Mac上我的/应用程序目录文件路径,但在正确的位置结束。。VAR IMG =要求(FS)readFileSync(uploadDir +'/上传/+ params.newFileName);
//文件被上传被multer在服务器上进行处理,并重新命名为这样的事情:fc5c5921bd0892f114cd7b6f0d39d9a3.gif附件:[{
    文件名:params.newFileName,
    文件路径:IMG
}]

我试过约一百名的变化根据我的研究在线主题,无论是和我没有得到任何附件可言,其结果如上所述,或通用依恋1.bin。我的 newFileName 参数是罚款。该文件存在于指定的目录。没有明确的错误。我肯定会喜欢一些指导:)

更新

下面是通往靠不住文件附件的步骤,从客户端向服务器

控制器方法:

  $ scope.Upload =功能()
{
    var文件= $ scope.fileModel;
    VAR的uploadURL ='/上传;    如果(formValid)
    {
        //上传它
        fileUpload.uploadFileToUrl(文件的uploadURL);
    }
};

里面有上传功能服务(我没能找到一种方法来提交与窗体的其余部分文件,因此上传单独处理,而我设置隐藏输入到价值multer改名的文件名,这是与表单提交):

  uploadFileToUrl:功能(文件的uploadURL)
{
    变种FD =新FORMDATA();
    fd.append(文件,文件);
    $ http.post(的uploadURL,FD,
    {
        transformRequest:angular.identity,
        标题:{
            内容类型:未定义
        }
    })    .success(功能(RES)
    {
        toastr.success(res.successMessage,成功);
        $('#文件名)。VAL(res.fileName)
        $('#文件名')触发器(输入)。
    })    .error(函数()
    {
        toastr.error(res.errorMessage,'错误');
    });
}

表单数据由两个方法,其中第一个存储在会话中PARAMS然后发送用户贝宝完成支付,并且其中访问这些会话变量的第二和构建并发送服务器上的处理电子邮件:

  //注意:离开了贝宝code,因为它是不相关
CompletePayment:功能(REQ,RES)
{
    //获取请求参数
    VAR PARAMS = req.body;    //在会话变量存储请求参数,所以我们可以送
    //确认电子邮件一旦付款完成
    req.session.requestFormData = {
        mediaType的:params.mediaType,
        名称:params.name,
        电子邮件:params.email,
        奉献:params.dedication,
        注意事项:params.notes,
        社会化媒体:params.socialMedia,
        newFileName:params.newFileName
    }
}

最后,构建并发送消息的方法 - 两人竟,主要的消息,并确认用户(很明显,占位符代替敏感信息):

  SendRequestEmail:功能(REQ,RES)
{
    VAR PARAMS = req.session.requestFormData;
    //我分裂nodemailer SMTP传输到关服务
    变种运输= EmailService.SetupTransport();    如果(PARAMS)
    {
        VAR mailOptions = {
            到:test@test.com,
            来自:'FROMNAME<'+ params.email +'>,
            主题:+ params.name'从请求,
            文字:有人要求的东西!回到'+ params.name +马上! +
                  的'\\ n \\ n类型:​​'+ params.mediaType +
                  '\\ n名称:'+ params.name +
                  '\\ nEmail:'+ params.email +
                  '\\ nDedication:'+ params.dedication +
                  '\\ Notes R5高校院系:'+ params.notes +
                  '\\ NCAN我们发布它:'+ params.socialMedia,
            附件:[{
                文件名:params.newFileName,
                //注:我改变这里的路径,一个应该在生产工作 - 部署,得到了相同的结果
                路径:'/服务器/上传/
            }]
        };        VAR confirmationMailOptions = {
            //一个更简单的以上版本 - 无附件,只是文本
        }        //发送请求电子邮件
        transport.sendMail(mailOptions,功能(错误,信息)
        {
            如果(错误){
                res.send({
                    nodemailerError:错误,
                    的errorMessage:哎呀!无论是电子邮件地址,您输入没有按\\'吨存在,或者interwebs行为不端。再试一次!'
                });
            }
            其他
            {
                //如果预订请求成功,发送确认用户
                transport.sendMail(confirmationMailOptions,功能(错误,信息)
                {
                    如果(错误){
                        的console.log(错误);
                    }其他{
                        res.send({
                            successMessage:确认消息发送到:'+ params.email
                        });                        req.session.destroy();
                    }
                });
            }
        });
    }
    其他
    {
        res.send({paramStatus:破坏'});
    }
}


解决方案

我知道我必须将图像正确的道路,并@hassansin指着我讲讲关于缓冲区正确的方向(与andris9提到的著名nodemailer <$的C $ C>内容:缓冲区在这个问题上我张贴的GitHub的网页,其中使我这个工作版本上的版本:

  VAR路径=要求('路径');
VAR uploadDir = path.dirname(require.main.filename);
。VAR IMG =要求(FS)readFileSync(uploadDir +'/上传/+ params.newFileName);附件:[{
    文件名:params.newFileName,
    内容:新的缓冲区(IMG)
}]

I'm trying to send an image attachment and it's coming through, but with no data. 0kb in size. That's using this code:

var path = require('path');
var uploadDir = path.dirname(require.main.filename); 
// This actually produces a filepath that starts at my /Applications dir on my Mac, but ends in the right spot.

var img = require("fs").readFileSync(uploadDir + '/uploads/' + params.newFileName);
// file was upload was handled on the server by multer and renamed to something like this: fc5c5921bd0892f114cd7b6f0d39d9a3.gif

attachments: [{
    filename: params.newFileName,
    filePath: img
}]

I've tried about a hundred variations on the theme based on my research online, and either I get no attachment at all, the result outlined above, or a generic attachment-1.bin. My newFileName param is fine. The file exists in the specified directory. There are no explicit errors. I would sure love some guidance :)

update

Here are the steps leading to the wonky file attachment, from the client to the server.

The controller method:

$scope.Upload = function()
{
    var file = $scope.fileModel;
    var uploadUrl = '/upload';

    if (formValid)
    {
        // Upload it
        fileUpload.uploadFileToUrl(file, uploadUrl);
    }
};

The service which houses the upload function (I wasn't able to find a way to submit the file with the rest of the form, so the upload is handled separately, and I am setting the value of a hidden input to the multer-renamed file name, which is submitted with the form):

uploadFileToUrl: function(file, uploadUrl)
{
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, 
    {
        transformRequest: angular.identity,
        headers: {
            'Content-Type': undefined
        }
    })

    .success(function (res)
    {
        toastr.success(res.successMessage, 'Success');
        $('#file-name').val(res.fileName)
        $('#file-name').trigger('input');
    })

    .error(function()
    {
        toastr.error(res.errorMessage, 'Error');
    });
}

The form data is handled on the server by two methods, the first of which stores the params in a session and then sends the user to Paypal to complete payment, and the second of which accesses those session variables, and constructs and sends the email:

// NOTE: leaving out the paypal code as it is not relevant
CompletePayment: function(req, res)
{
    // Get the request params
    var params = req.body;

    // Store request params in session variables so we can send 
    // confirmation emails once payment has been completed
    req.session.requestFormData = {
        mediaType: params.mediaType,
        name: params.name,
        email: params.email,
        dedication: params.dedication,
        notes: params.notes,
        socialMedia: params.socialMedia,
        newFileName: params.newFileName
    }
}

Finally, the method that constructs and sends the message - two actually, the main message, and the confirmation to the user (obviously replacing sensitive info with placeholders):

SendRequestEmail: function(req, res)
{
    var params = req.session.requestFormData;
    // I split the nodemailer SMTP transport off into a service
    var transport = EmailService.SetupTransport();

    if (params)
    {
        var mailOptions = {
            to: 'test@test.com',
            from: 'FromName <'+params.email+'>',
            subject: 'Request from ' + params.name,
            text: 'Someone has requested something! Get back to ' + params.name + ' right away!' +
                  '\n\nType: ' + params.mediaType + 
                  '\nName: ' + params.name +
                  '\nEmail: ' + params.email + 
                  '\nDedication: ' + params.dedication +
                  '\nNotes: ' + params.notes +
                  '\nCan We Post It: ' + params.socialMedia,
            attachments: [{
                filename: params.newFileName,
                // NOTE: I changed the path here to one that should work in production - deployed and got the same result
                path: '/server/uploads/'
            }]
        };

        var confirmationMailOptions = {
            // A much simpler version of above - no attachments, just text
        }

        // Send the request email
        transport.sendMail(mailOptions, function(error, info)
        {
            if(error){
                res.send({
                    nodemailerError: error, 
                    errorMessage: 'Oops! Either the email address you entered doesn\'t exist, or the interwebs are misbehaving. Try again!'
                });
            }
            else
            {
                // If booking request was successful, send the confirmation to the user
                transport.sendMail(confirmationMailOptions, function(error, info)
                {
                    if (error) {
                        console.log(error);
                    } else {
                        res.send({
                            successMessage: 'Confirmation message sent to: ' + params.email
                        });

                        req.session.destroy();
                    }
                });
            }
        });
    }
    else
    {
        res.send({paramStatus: 'destroyed'});
    }
}

解决方案

I knew I had the right path to the image, and @hassansin pointed me in the right direction about the buffer (and andris9 of the famed nodemailer mentioned content: Buffer in the version of this question I posted on the GitHub page. Which led me to this working version:

var path = require('path');
var uploadDir = path.dirname(require.main.filename); 
var img = require("fs").readFileSync(uploadDir + '/uploads/' + params.newFileName);

attachments: [{
    filename: params.newFileName,
    content: new Buffer(img)
}]

这篇关于Nodemailer图像附件没有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆