Attachment encoding wrong
AlexWarrior1 opened this issue · 2 comments
Hi!
i'm working with mailkit for download invoices from inbox email, but in some cases when it download the xml it does with characters weird as show below
<cfdi:Comprobante xmlns:cfdi=3D"http://www.sat.gob.mx/cfd/4" =
xmlns:xsi=3D"http://www.w3.org/2001/XMLSchema-instance" =
xsi:schemaLocation=3D"http://www.sat.gob.mx/cfd/4 =
http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd" Version=3D"4.0" =
Fecha=3D"2023-09-22T00:00:00" Serie=3D"A" Folio=3D"5500427" =
this is the correct xml
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd" Version="4.0" Fecha="2023-09-22T00:00:00" Serie="A" Folio="5500427"
i'm running de app in windows, and de language is c# .Net Core
the version of mimekit is NetCore.MailKit 2.1.0
this is how i read the attachments
var attachmentStream = mimePart.Content.Stream;
// Specify the file path where you want to save the attachment
string filePath = "c:\\test.xml"; // Replace with your desired file path and extension
// Use Ude to auto-detect the encoding
var detector = new CharsetDetector();
detector.Feed(attachmentStream);
detector.DataEnd();
// Get the detected encoding
string detectedEncoding = detector.Charset;
// Reset the attachment stream position
attachmentStream.Seek(0, SeekOrigin.Begin);
// Create a FileStream to write the attachment content to the file with the detected encoding
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
using (var writer = new StreamWriter(fileStream, Encoding.GetEncoding(detectedEncoding)))
{
// Read from the attachment stream and write it to the file stream with the detected encoding
using (var reader = new StreamReader(attachmentStream, Encoding.GetEncoding(detectedEncoding)))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
writer.WriteLine(line);
}
}
}
// Close the streams
attachmentStream.Close();
any idea that what i am doing wrong?
thanks!
The MimePart.Content.Stream is encoded using the MimePart.Content.Encoding mechanism, so if it isn't "Default", then you need to decode it.
MimeContent has 2 ways of doing this:
- Use the MimeContent.DecodeTo(Stream) method which decodes into an output stream.
- Use MimeContent.Open() which returns a stream that will decode the content as you read from it.
thanks a lot!
it worked from me the first option (MimeContent.DecodeTo(Stream))
regards!