tags:

views:

355

answers:

2

I'm trying to attach a PDF attachment to an email being sent with System.Net.Mail. The attachment-adding part looks like this:

using (MemoryStream pdfStream = new MemoryStream())
{
    pdfStream.Write(pdfData, 0, pdfData.Length);

    Attachment a = new Attachment(pdfStream, 
        string.Format("Receipt_{0}_{1}.pdf", jobId, DateTime.UtcNow.ToString("yyyyMMddHHmm")));

    msg.Attachments.Add(a);

    SmtpClient smtp = new SmtpClient(serverName, port);
    smtp.Credentials = new NetworkCredential(fromEmailName, fromEmailPassword);
    smtp.Send(msg);
}

The problem is that the attachment gets corrupted on the other end. I found some discussion of this problem here, however the solution mentioned on that page used System.Web.Mail.MailAttachment, which was made obsolete in .NET 2.0.

I've tried changing the TransferEncoding in the Attachment class (which replaces MailAttachment), but had no luck. Has anyone solved this on .NET 2.0?

+1  A: 

Have you tried doing a pdfStream.Seek(0,SeekOrigin.Begin) before creating the attachment to reset the stream to the beginning?

tvanfosson
Yup, that was it. I guess the whole encoding thing was a red herring :)
mlenarz
+1  A: 

Have you checked to make sure that the PDF document isn't already corrupted in the pdfData array? Try writing that to a file then opening it.

Cheers
Kev

Kev
Yeah, tried that. Thanks for the suggestion, though.
mlenarz