pkarsai

MIME parsing with PowerShell

Oct 8th, 2014
2,946
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3. Parses a MIME email document into a CDO.Message object.
  4.  
  5. .DESCRIPTION
  6. Reads the parameter MIME file into a CDO.Message (CDO for Windows 2000) COM object.
  7. The returned CDO.Message object can be used to access the MIME file contents in decoded form.
  8.  
  9. .PARAMETER FileSpec
  10. The file specification to be parsed, e.g. "C:\demo\test.eml".
  11.  
  12. .EXAMPLE
  13. Get-ParsedMimeFile -FileSpec "C:\demo\test.eml"
  14.  
  15. .OUTPUTS
  16. A CDO.Message object representing the parsed MIME document. See http://msdn.microsoft.com/en-us/library/ms526453(v=exchg.10).aspx
  17.  
  18. .LINK
  19. http://msdn.microsoft.com/en-us/library/ms526453(v=exchg.10).aspx
  20. #>
  21. function Get-ParsedMimeFile([string] $FileSpec)
  22. {
  23.     # read MIME into a byte array
  24.     $mimeBytes = [System.IO.File]::ReadAllBytes($FileSpec);    
  25.  
  26.     # load byte array into an ADODB stream, which will act as data source for CDO
  27.     $stream = New-Object -ComObject "ADODB.Stream";
  28.     $stream.Open();
  29.     $stream.Type = 1; # adTypeBinary, i.e. binary stream
  30.     $stream.Write($mimeBytes);
  31.     $stream.Flush();
  32.     $stream.SetEOS();
  33.  
  34.     # create CDO.Message and assign stream as data source
  35.     $message = New-Object -ComObject "CDO.Message";
  36.     try
  37.     {
  38.         $message.DataSource.OpenObject($stream, "_Stream");      
  39.     }
  40.     finally
  41.     {
  42.         $stream.Close();
  43.     }
  44.  
  45.     return $message;
  46. }
  47.  
  48. # DEMO
  49. $message = Get-ParsedMimeFile -FileSpec "C:\demo\test.eml";
  50.  
  51. # dump subject
  52. Write-Output "Email subject: $($message.Subject)";
  53.  
  54. # dump all parsed header fields
  55. foreach($field in $message.Fields) {
  56.     Write-Output "Field $($field.Name) => $($field.Value)";
  57. }
  58.  
  59. # dump decoded email text body
  60. Write-Output "Text body follows:`r`n$($message.TextBody)";
  61.  
  62. # dump decoded email HTML body
  63. Write-Output "HTML body follows:`r`n$($message.HtmlBody)";
Advertisement
Add Comment
Please, Sign In to add comment