thenodecoder thenodecoder - 4 months ago 45
Node.js Question

Send email with image attachment in node.js

Currently I am able to send emails in node.js using code along the lines of:

var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "gmail.user@gmail.com",
pass: "gmailpass"
}
});

smtpTransport.sendMail({
from: "My Name <me@example.com>", // sender address
to: "Your Name <you@example.com>", // comma separated list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world ✔" // plaintext body
}, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});


How can I send an attachment of an uploaded image from an html form in this email? Also, can I send the image in the email without uploading it to the serve? If not, that's okay. This is my html form:

<form id="mainForm">
<input type="file" id="fileUpload">
<input type="submit" id="submit" name="submit">
</form>


How can I take the file and include it in the email I send using node.js?

Answer

You could try something like this. Use busboy to get the file and then once you get the file convert it to base64 and add it to the attachment property for you mail options. The only thing is i dont know if the file argument comes back as a buffer. If it doesnt you just need to convert that file to base 64 and will be able to send it as an attachement

var app = express();
var Busboy = require('busboy');
var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
     auth: {
         user: "gmail.user@gmail.com",
         pass: "gmailpass"
     }
});

app.post('/email', function(req, res){
    var busboy = new Busboy({ headers: req.headers });
    var attachments = [];

    var mailOptions = {
        from: "My Name <me@example.com>", // sender address
        to: "Your Name <you@example.com>", // comma separated list of receivers
        subject: "Hello ✔", // Subject line
        text: "Hello world ✔" // plaintext body
    };

    busboy
        .on('file', function(fieldname, file, filename, encoding, mimetype){
            attachments.push({
               filename: filename,
               content: file.toString('base64'),
               encoding: 'base64'
            });
        })
        .on('finish', function() {
            mailOptions.attachments = attachments;
            smtpTransport.sendMail(mailOptions, function (err, info) {
               if (err) {
                   //handle error
               }
                // email sent
           });
        });
});
Comments