Advertisement
pkarsai

MIME parsing with PowerShell

Oct 8th, 2014
783
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. peter.karsai@vamsoft.com
  21. #>
  22. function Get-ParsedMimeFile([string] $FileSpec)
  23. {
  24.     # read MIME into a byte array
  25.     $mimeBytes = [System.IO.File]::ReadAllBytes($FileSpec);    
  26.  
  27.     # load byte array into an ADODB stream, which will act as data source for CDO
  28.     $stream = New-Object -ComObject "ADODB.Stream";
  29.     $stream.Open();
  30.     $stream.Type = 1; # adTypeBinary, i.e. binary stream
  31.     $stream.Write($mimeBytes);
  32.     $stream.Flush();
  33.     $stream.SetEOS();
  34.  
  35.     # create CDO.Message and assign stream as data source
  36.     $message = New-Object -ComObject "CDO.Message";
  37.     try
  38.     {
  39.         $message.DataSource.OpenObject($stream, "_Stream");      
  40.     }
  41.     finally
  42.     {
  43.         $stream.Close();
  44.     }
  45.  
  46.     return $message;
  47. }
  48.  
  49. # DEMO
  50. $message = Get-ParsedMimeFile -FileSpec "C:\demo\test.eml";
  51.  
  52. # dump subject
  53. Write-Output "Email subject: $($message.Subject)";
  54.  
  55. # dump all parsed header fields
  56. foreach($field in $message.Fields) {
  57.     Write-Output "Field $($field.Name) => $($field.Value)";
  58. }
  59.  
  60. # dump decoded email text body
  61. Write-Output "Text body follows:`r`n$($message.TextBody)";
  62.  
  63. # dump decoded email HTML body
  64. Write-Output "HTML body follows:`r`n$($message.HtmlBody)";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement