Convert System.Net.MailMessage to OpenPop.Mime.Message

972 Views Asked by At

Ho do I Can Convert

System.Net.MailMessage

to

OpenPop.Mime.Message

to create new Message of OpenPop.Mime.Message. First , I use below code to Extract RawMessage of the MailMessage, then send It to constructor of the OpenPop.Mime.Message to create an instance of the Message, But if email contain Persian content, for example the Display Name of the Sender is Persian ("مسعود بهرامی"), After convert sender is changed to "??????????"`

private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
    private static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
    private static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(Stream) }, null);
    private static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags);
    private static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", Flags);

    /// <summary>
    /// A little hack to determine the number of parameters that we
    /// need to pass to the SaveMethod.
    /// </summary>
    private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;

    /// <summary>
    /// The raw contents of this MailMessage as a MemoryStream.
    /// </summary>
    /// <param name="self">The caller.</param>
    /// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
    public static byte[] RawMessage(this MailMessage self)
    {
        var result = new MemoryStream();

        var mailWriter = MailWriterConstructor.Invoke(new object[] { result });
        SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);

        return null;

        //result = new MemoryStream(result);
        //result = new MemoryStream(Encoding.UTF8.GetBytes(result.ToArray().ToString()));

        CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null);

        //return result;
    }
1

There are 1 best solutions below

2
On

It doesn't look like System.Net.MailMessage exposes any methods that'll do the byte[] formatting for you, so you'll have to create a ToByteArray method to construct a byte array that you can pass to the constructor of OpenPop.Mime.Message in order to create a message object. You can deduce the format of the array that you need, from the following system:

Converting a Gmail API Message into an OpenPop Mime message

This doesn't exactly solve your problem, but I hope it gives you enough to work with.