0

I have to decode the following code and then attach it as PDF in an email in C#.

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var smtpClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("Mail@mail.com", "me@mail.com", "Just testing", "See attachment..."))
{
    writer.WriteLine("0x255044462D312E340A25E2E3CFD30A332030206F626A203C3C2F4[...]");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
    Attachment attach = new Attachment(stream, ct);
    message.Attachments.Add(new Attachment(stream, "filename.pdf", "application/pdf"));

    smtpClient.Port = 25;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Host = ConfigurationManager.AppSettings["MailHost"];
    smtpClient.Send(message);
}

The email is sent but when I want to open it it tells me that the file is damaged.

Did someone make this kind of decoding of a PDF file?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Andy
  • 751
  • 1
  • 12
  • 25
  • 4
    A PDF file is a *binary* file. The code isn't decoding anything, it's sending a weird looking string as an attachement. I suspect you wanted to send the bytes of a PDF file but sent a *string representation* of the bytes instead – Panagiotis Kanavos Jun 27 '18 at 15:46
  • 5
    You appear to be writing a hexadecimal *string* to a stream and treating it as a PDF, this isn't correct. *If* the hex string represents a vaild PDF you need to translate it to the bytes it encodes, then write that. (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array) – Alex K. Jun 27 '18 at 15:46
  • This really all depends on what your PDF is, where it's stored and how you intend to read it. None of that code is here so we can't help – Liam Jun 27 '18 at 15:48
  • 2
    What are you trying to do anyway? If you want to send an unchaning file, store it locally and send it as an attachment. Or store it as a binary resource of the application. If you want to generate a PDF dynamically though you can't do it by manipulating the bytes. – Panagiotis Kanavos Jun 27 '18 at 15:48
  • 1
    Thank you! That string was only the representation of the binary data that it obtained from SQL. I solved it by casting the data directly: bytes bts= (byte []) dataRow["binarydata"] and then fill the bytes array to Stream: var stream = new MemoryStream(bts) – Andy Jun 27 '18 at 18:24

0 Answers0