Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

corrupted email attachments in .NET

Tags:

c#

.net

smtp

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?

like image 285
mlenarz Avatar asked Nov 21 '08 00:11

mlenarz


1 Answers

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

like image 172
tvanfosson Avatar answered Sep 22 '22 04:09

tvanfosson