Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MailMessage to MemoryStream in .net core

I am using the .Net Core 1.2 with Amazon SES(SimpleEmail) to send the Emails(Raw Emails).

Below is the working code version we have used in .net framework 4.5:

   public MemoryStream ConvertMailMessageToMemoryStream(MailMessage message)
    {
        Assembly assembly = typeof(SmtpClient).Assembly;

        Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

        MemoryStream fileStream = new MemoryStream();

        ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);

        object mailWriter = mailWriterContructor.Invoke(new object[] { fileStream });

        MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);

        sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);

        MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);

        closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);

        return fileStream;

    }

But in .Net Core 1.2 we are unable to get reference for class Assembly of SmtpClient and System.Net.Mail.MailWriter. Below is working in regular .net framework:

Assembly assembly = typeof(SmtpClient).Assembly;

In .Net Core, since SmtpClient is available in MailKit, we have referenced it and gives the following error:

'Type' does not contain a definition for 'Assembly' and no extension method 'Assembly' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

Is there any way in .Net Core to convert the MailMessage to MemoryStream?

like image 755
Raguvaran Devendiran Avatar asked Aug 04 '17 04:08

Raguvaran Devendiran


1 Answers

Looks like there is no constructor accepting only one argument in dotnet core 5.0, try this.

ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream), typeof(bool) }, null);

    object mailWriter = mailWriterContructor.Invoke(new object[] { fileStream,true });
like image 148
Dozcent Avatar answered Nov 20 '22 19:11

Dozcent