Search code examples
node.jsxmltypescriptemail-attachmentsnodemailer

Generate XML file and attach it in email (Node.js)


How one can create an XML file and attach it in email by using nodemailer?

This is the format of the XML file:


<?xml version="1.0" encoding="UTF-8"?>
<CaseData>
   <CaseNo>329388m1</CaseNo>
</CaseData>

The code to compose an email:

const mailOptions = {
    from: 'andreifletcherssolicitors@gmail.com',
    to: '97andreienache@gmail.com',
    subject: 'Test',
    text: 'Hello World!'
};


Solution

  • You can use xmlbuilder to make it easier to generate xml

    var builder = require('xmlbuilder');
    
    var obj = {
      CaseData: {
        CaseNo: '329388m1'
      }
    };
    
    var xml = builder.create(obj).end({ pretty: true});
    console.log(xml);
    

    and then attach it with nodemailer like this

    let message = {
        ...
        attachments: [
            {
                filename: 'myxmlfile.xml',
                content: xmlStringAbove,
                contentType: 'text/xml'
            }
        ]
    }