2019-12-08 21:23:54 +01:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Net.Mail;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace Swan {
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Extension methods.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class SmtpExtensions {
|
|
|
|
|
private static readonly BindingFlags PrivateInstanceFlags = BindingFlags.Instance | BindingFlags.NonPublic;
|
|
|
|
|
|
2019-12-04 18:57:18 +01:00
|
|
|
|
/// <summary>
|
2019-12-08 21:23:54 +01:00
|
|
|
|
/// The raw contents of this MailMessage as a MemoryStream.
|
2019-12-04 18:57:18 +01:00
|
|
|
|
/// </summary>
|
2019-12-08 21:23:54 +01:00
|
|
|
|
/// <param name="this">The caller.</param>
|
|
|
|
|
/// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
|
|
|
|
|
public static MemoryStream ToMimeMessage(this MailMessage @this) {
|
|
|
|
|
if(@this == null) {
|
|
|
|
|
throw new ArgumentNullException(nameof(@this));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
MemoryStream result = new MemoryStream();
|
|
|
|
|
Object mailWriter = MimeMessageConstants.MailWriterConstructor.Invoke(new Object[] { result });
|
|
|
|
|
_ = MimeMessageConstants.SendMethod.Invoke(@this, PrivateInstanceFlags, null, MimeMessageConstants.IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);
|
|
|
|
|
|
|
|
|
|
result = new MemoryStream(result.ToArray());
|
|
|
|
|
_ = MimeMessageConstants.CloseMethod.Invoke(mailWriter, PrivateInstanceFlags, null, Array.Empty<Object>(), null);
|
|
|
|
|
result.Position = 0;
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
internal static class MimeMessageConstants {
|
2019-12-04 18:57:18 +01:00
|
|
|
|
#pragma warning disable DE0005 // API is deprecated
|
2019-12-08 21:23:54 +01:00
|
|
|
|
public static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
|
2019-12-04 18:57:18 +01:00
|
|
|
|
#pragma warning restore DE0005 // API is deprecated
|
2019-12-08 21:23:54 +01:00
|
|
|
|
public static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(PrivateInstanceFlags, null, new[] { typeof(Stream) }, null);
|
|
|
|
|
public static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", PrivateInstanceFlags);
|
|
|
|
|
public static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", PrivateInstanceFlags);
|
|
|
|
|
public static readonly Boolean IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-12-04 18:57:18 +01:00
|
|
|
|
}
|