Perl read a file and send e-mail -
i have log file of below format
d12345 joe@gmail.com c67890 mary@gmail.com b45678 don@gmail.com a12309 joe@gmail.com f45670 mary@gmail.com f45470 joe@gmail.com
currently i'm able send e-mail below e-mail body content
your product id: $product_id
($product_id d12345, a12309, f45470 , c67890, f45670)
problem 'n' e-mails sent user if e-mail id present n times in log file.
example : 2 e-mails sent mary@gmail.com , 3 e-mails sent joe@gmail.com
i want send 1 e-mail users having product ids, if single e-mail id occurs multiple times in output file, like
your product ids: c67890, f45670 mary@gmail.com
and
your product ids: d12345, a12309, f45470 joe@gmail
my current code snippet
open $fh, '<', "output.txt" or die "could not open file: $!"; while (my $line = <$fh>) { ($product_id, $to_email) = $line =~ /(\w\d+)\t(\s+)/; $mailfrom = 'myemail@domain.com'; $subject = "product id details"; $message = "your product ids: $product_id"; %mail = ( => $to_email, => $mailfrom, subject => $subject, message => $message ); $mail{smtp} = 'mail.myorg.com'; sendmail(%mail)or die $mail::sendmail::error; } close $fh;
suggestions appreciated. in advance.
you must aggregate information log file hash before sending mails
here's example code dumps %mail
hash instead of calling sendmail
can see results
use strict; use warnings 'all'; use data::dump; %users; { open $fh, '<', "output.txt" or die "could not open file: $!"; while ( <$fh> ) { ($prod, $user) = split; push @{ $users{$user} }, $prod; } } # convert arrays of product codes comma-separated strings # $_ = join ', ', @$_ values %users; while ( ($user, $prods) = each %users ) { %mail = ( => $user, => 'myemail@domain.com', subject => 'product id details', message => "your product ids: $prods", smtp => 'mail.myorg.com', ); dd \%mail #sendmail(%mail) or die $mail::sendmail::error; }
output
{ => "myemail\@domain.com", message => "your product ids: d12345, a12309, f45470", smtp => "mail.myorg.com", subject => "product id details", => "joe\@gmail.com", } { => "myemail\@domain.com", message => "your product ids: b45678", smtp => "mail.myorg.com", subject => "product id details", => "don\@gmail.com", } { => "myemail\@domain.com", message => "your product ids: c67890, f45670", smtp => "mail.myorg.com", subject => "product id details", => "mary\@gmail.com", }
Comments
Post a Comment