【问题标题】:How to Send Images as Attachments with Mailgun and Node.js?如何使用 Mailgun 和 Node.js 将图像作为附件发送?
【发布时间】:2019-06-13 06:32:03
【问题描述】:

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

我使用 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
        };

预期的结果是一封附有新帖子图片的电子邮件,或者在本例中是该帖子的单个图片。

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

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 '

【问题讨论】:

  • 如果您有图片 URL 并且它是公开的,那么您可以在 HTML 正文中显示您的图片。还有一个选项,您可以在本地 /tmp 目录中下载图像,然后在附件键中传递图像 url:附件:['/tmp/abc.png','/tmp/xyz.jpg']

标签: node.js mongodb express mailgun cloudinary


【解决方案1】:

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
};

这是来自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

【讨论】:

  • @JordanPisani 你是否让它处理多个图像?
  • @jhk 是的,请参考this thread
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2020-10-01
  • 2018-09-05
  • 1970-01-01
相关资源
最近更新 更多