How to insert the contents of an Excel spreadsheet into an email in C #?
I have C # code that sends an email. In the body of the email, I want to send the contents of an excel sheet.
One way to do this is to create an html table with html strings for each record in the excel file and insert that HTML into the body of the email.
Is there an easier way to do this? Something where I can just give the path to the Excel sheet and the table itself will be copied into the body of the email?
Thanks.
The simplest is to use the Workbook.SendMail () method.
Sample code:
Excel.Workbook myWorkbook = xlApp.Workbooks["Book1.xls"];
string recipients = "johndoe@email.com";
string subject = "Proposal for Review";
bool returnReceipt = false;
myWorkbook.SendMail(recipients, subject, returnReceipt);
Note that the parameter is recipients
actually typed like System.Object
, so the passed argument might be string[]
if you have multiple recipients.
Sources:
(1) http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.sendmail(VS.80).aspx
(2) http://msdn.microsoft.com/en-us/library/bb178034.aspx
You can also have a look at Ron de Bruin Sending mail from Excel using CDO , but the Workbook.SendMail () method is really the simplest.
Hope it helps ...
Mike
a source to share
You can try to do it through ADODB connection with excel sheet. http://support.microsoft.com/kb/306023
- Open the recordset in an Excel worksheet.
- Call recordset.GetString ( http://www.devguru.com/technologies/ado/quickref/recordset_getstring.html ). This dumps the contents of the sheet to a string.
It might be shorter (in length) and then the code you were planning, which is probably related to Excel automation.
a source to share
it's not built in, but you can try the attachment class: http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx
alternatives are to use third party excel control to open it, copy data and paste into post.
a source to share
I assume you want to do this natively in C #.
I find it best to use Office Automation in C # to save the table in HTML file format. Then you can open this file with a StreamReader object and insert text into the body of your message.
Microsoft has an article on Excel Automation, with some code examples you started with:
How to automate Microsoft Excel with Microsoft Visual C # .NET http://support.microsoft.com/kb/302084
a source to share