如何使用Mailgun和Node.js将图像作为附件发送?

时间:2019-01-19 01:27:48

标签: node.js mongodb express mailgun cloudinary

我正在尝试将图像作为附件发送给电子邮件,但是我在弄清楚如何完成此操作时遇到了麻烦。

我正在使用Mailgun发送邮件,使用Cloudinary上传图像,使用MongoDB作为我的数据库,使用Node.js / Express作为我的后端。

用户流程如下:

  • 用户将图片提交到网站上
  • 图片通过Cloudinary上传,每个图片的直接链接保存在MongoDB数据库中
  • 邮件通过Mailgun发送出去,以通知用户新帖子,并带有指向正文图像的链接

显然这是不理想的,因为您需要单独单击每个链接以查看和下载图像。我想将它们直接附加到电子邮件中,以便用户更轻松地下载图像。

我看过Mailgun的文档,但似乎不能将非本地图像作为附件发送。有什么我想念的吗?

我尝试对Mailgun使用'inline'和'attachment'参数,但最终出现一条错误消息,指出无法找到文件/目录。

var pictures = [];
        post.images.forEach(function(photos){
            pictures.push(photos + " ");
            return pictures;
        });

var attch = new mailgun.Attachment({data: pictures[0], filename: "picture"});
        var data = {
            from: "email <email@email.com>",
            to: "email@email.com",
            subject: 'this is an email',
            html: 'here is a new post and here are the images in that post',
            attachment: attch
        };

预期结果是一封包含新帖子图像的电子邮件,或者在这种情况下,是该帖子中的一张图像。

实际结果是此错误消息:

events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: ENOENT: no such file or directory, stat 'https://res.cloudinary.com/user/image/upload/image.jpg '

1 个答案:

答案 0 :(得分:2)

mailgun.js软件包将接受附件作为文件路径,缓冲区和流。要通过外部网址附加图片,请使用流,

var request = require('request');
var image = request(pictures[0]);
var data = {
    from: "email <email@email.com>",
    to: "email@email.com",
    subject: 'this is an email',
    html: 'here is a new post and here are the images in that post',
    attachment: image
};

这是mailgun.js

中的示例代码
var request = require('request');
var file = request("https://www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'serobnic@mail.ru',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomeness!',
  attachment: file
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

参考:https://www.npmjs.com/package/mailgun-js#attachments