Generate Excel and Add As Email Attachment

Nov 13, 2012 at 1:11 PM

Hi,

I was wondering if it's possible in ClosedXML to generate an Excel file and rather than saving to a fileshare, attach the file to an email directly?  I would like to avoid setting up a service account with special permissions to a fileshare.

Thanks much!

Heather

Coordinator
Nov 13, 2012 at 2:55 PM
Edited Nov 13, 2012 at 2:56 PM

If you can attach a file from a memory stream then you could do that instead.

Nov 13, 2012 at 7:53 PM

I attempted using memorystream since I just want the file in memory rather than a drive somewhere. My issue now is that the attachment is giving an error that the “file format or file extension is not valid”. I tried using both “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet” and then “application/vnd.msexcel” for the content types but both give the same results. Can you point me to someplace I can figure out how to fix this issue?

Thanks so much!

Heather

From: MDeLeon [email removed]
Sent: Tuesday, November 13, 2012 9:56 AM
To: Uhles, Heather
Subject: Re: Generate Excel and Add As Email Attachment [closedxml:403035]

From: MDeLeon

If you can attach a file from a file stream then you could do that instead.

Aug 7, 2013 at 5:42 PM
I had a similar problem. Solved with highlighted line of code before creating the attachment from memory stream.
using (MemoryStream memoryStream = new MemoryStream())
{
    MailMessage mailMessage = new MailMessage(smtpFrom, smtpTo);

    mailMessage.Subject = subject;
    mailMessage.Body = body;

    __memoryStream.Seek(0, SeekOrigin.Begin);__
    Attachment attachment = new Attachment(memoryStream, "<filename>.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    mailMessage.Attachments.Add(attachment);

    SmtpClient smtpClient = new SmtpClient(smtpServer);
    smtpClient.Send(mailMessage);

    memoryStream.Close();
}