MailMessage: To RAW

Converting a MailMessage object to Raw (Byte) for SendGrid or AWS SES.

function ConvertTo-RawDataMailMessage {
    [CmdletBinding()]
    [OutputType([Byte[]])]
    param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0)]
        [Net.Mail.MailMessage] $mailMessage
    )
    process {
        
        $assembly = [System.Net.Mail.SmtpClient].Assembly
        $mailWriterType = $assembly.GetType("System.Net.Mail.MailWriter")
        # Based upon the C# implementation
        # https://stackoverflow.com/questions/1264672/how-to-save-mailmessage-object-to-disk-as-eml-or-msg-file/70582581#70582581
        $bindingFlags = [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic
        $typeArray = ([System.Type]::GetType("System.IO.Stream"), [System.Type]::GetType("System.Boolean"))
        $mailWriterConstructor = $mailWriterType.GetConstructor($bindingFlags, $typeArray)
        $MemoryStream = New-Object -TypeName "System.IO.MemoryStream"
        [System.Array]$paramArray = ($MemoryStream)
        $paramArray += $true
        $mailWriter = $mailWriterConstructor.Invoke($paramArray)
        $messageType = $mailMessage.GetType()
        $sendMethod = $messageType.GetMethod("Send", $bindingFlags)
        [System.Array]$sendParams = ($mailWriter, $true, $true)
        $sendMethod.Invoke($mailMessage, $bindingFlags, $null, $sendParams, $null)
        $closeMethod = $mailWriter.GetType().GetMethod("Close", $bindingFlags)
        $closeMethod.Invoke($mailWriter, $bindingFlags, $null, @(), $null)
        # [System.Text.Encoding]::UTF8.GetString($MemoryStream.ToArray())
        $raw_data = $MemoryStream.ToArray()
        $MemoryStream.Dispose()
        Remove-Variable MemoryStream
        $raw_data
    }
}