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

Jor*_*ani 3 mongodb node.js express cloudinary mailgun

我正在尝试将图像作为电子邮件的附件发送,但我无法弄清楚如何完成此操作。

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

用户流程是这样的:

  • 用户向网站提交图片
  • 图片通过 Cloudinary 上传,每张图片的直接链接保存在 MongoDB 数据库中
  • 邮件通过 Mailgun 发出,通过正文中的图像链接通知用户新帖子

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

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

我曾尝试为 Mailgun 使用“内联”和“附件”参数,但最终得到一条错误消息,指出无法找到文件/目录。

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
        };
Run Code Online (Sandbox Code Playgroud)

预期的结果是一封带有新帖子附加图像的电子邮件,或者在这种情况下是来自该帖子的单个图像。

实际结果是这个错误信息:

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 '
Run Code Online (Sandbox Code Playgroud)

Şiv*_*kĂr 8

mailgun.js包将接受附件作为文件路径、缓冲区和流。要从外部 URL 使用流附加您的图像,

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
};
Run Code Online (Sandbox Code Playgroud)

这是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);
});
Run Code Online (Sandbox Code Playgroud)

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