HOW TO send an email with a Word or Excel file attachment built on the fly

This question was asked on a Forum and the poster faced a situation where some hundred invoices had to be sent as an attachment to different receipients each pre-filled with user specific data retreived from the database. Creating these invoices manually, saving the files and picking them up programmatically to be emailed was the obvious time-consuming solution. It also carries the additional overhead of having to delete the files after emailing those attachments.

I remembered reading that with System.Net.Mail, attachments could be created from a stream. Now there is also a cool re-usable method "DataTable2ExcelString" which can be used to generate an Excel sheet (or Word document) programmatically. I packed both of these ideas into a quick and dirty code snippet as a proof of concept.

The email with the dynamically generated attachment can be copied to the sender's address also if proof of delivery or archiving is required.

Related links:
HOW TO implement "Download as Word/Excel" functionality through a web page
HOW TO add a header or footer to a dynamically generated Word document
HOW TO generate a Word document dynamically with user submitted text formatted with Free Text Box
HOW TO send an email programmatically using C# with GMail

Comments