creampiedonut
creampiedonut

Reputation: 327

How to to attach URL image to an email using nodemail?

I am trying to attach an image via url link to an email I am sending. Here is my code,

var nodemailer = require("nodemailer");
var fs = require("fs");
var request = require("request");

exports.index = function index(req, res){
    var transporter = nodemailer.createTransport("SMTP", {
        service: 'yahoo',
        auth: {
            user: '[email protected]',
            pass: '_'
        }
    });
    var attachedfile;

        request.get('http://i.imgur.com/iIAS1wE.jpg', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                attachedfile = body;
            }
        });
        var options = {
            from: '[email protected]',
            to: '[email protected]',
            subject: 'hello',
            text: 'hello! See attached files',
            attachments: [
            {filename: 'starwars.jpg', contents: attachedfile }]
        }
        transporter.sendMail(options , function(err, response){
        if(err){
            console.log(err);
        } else {
            console.log('Message sent: ' + response.message);
        }
        transporter.close();
        });
    res.render('email/index');
}

But there is no image when I check the email...what am I doing wrong here? Thanks

Upvotes: 2

Views: 4064

Answers (2)

nipunasudha
nipunasudha

Reputation: 2617

Nodemailer automatically fetches and attaches files from provided URLs. Here's a detailed guide of different ways to attach files.

attachments: [{
        filename: "iIAS1wE.jpg",
        path: "http://i.imgur.com/iIAS1wE.jpg",
    }]

Upvotes: 2

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24650

You don't need to fetch manually the files (in case you dont send bulk emails), nodemailer can do it for you:

 attachments: [
            {path: 'http://i.imgur.com/iIAS1wE.jpg'}]

Upvotes: 0

Related Questions