Search code examples
perloutlookmsg

Reading and text matching Outlook .msg file in Perl


I am having trouble text matching .msg files using Perl. The first block of code works to print the entire message, but I just need the file name if it contains a certain string.

    use warnings;
    use strict;
    use Email::Outlook::Message;
    use Email::MIME;

    my $sourceDir = "c:/temp";

    open_msg("test.msg");

    sub open_msg {
       my $verbose = 0;
       my $msgFile = shift;
       my $origMsg = new Email::Outlook::Message "$sourceDir/$msgFile", $verbose or die "$!";
       my $mime = $origMsg->to_email_mime;
       print $mime->as_string;
       return ($origMsg);
    }

The .msg files are in a folder (on Windows). I have used below code to print the file names of .txt files, but I need to use something similar for .msg files.

#works for .txt files
my @files = glob "C:/temp";

foreach my $file (@files) {
open   (FILE, "$file");
while(my $line= <FILE> ){
    print "$file" if $line =~ /test_string/;
}
close FILE; 
} 

Thanks!


Solution

  • I don't have any .msg file handy to test with but how about replacing this line:

    print $mime->as_string;
    

    ...with a statement like this?

    print $mime->as_string if $mime->as_string =~ /test_string/;
    

    This should do the trick as far as "print its contents if it contains test_string" is concerned.

    If you also want to loop over the whole list of *.msg files, try something like this:

    my @files = glob "C:/temp";
    
    foreach my $file (@files) {
        open_msg($file);
    }