Hello fellow monks,
I wrote a small piece of code that emails images from a directory. Some of the email are a few megabytes and thus the transfers are a little slow. I needed some form of indicator to show that the script was running. Ohh, and by the way.. Message size is not an issue because the mail server accepts email sizes up to 100meg..
One ideal solution would be to use Term::ProgressBar which displays very nice status information. Unfortunately, you have to call an update routine. Since I am sending only one message, I dont know how I could utilize such a solution without modify the MIME::Lite module in some way.
My only solution I could think about would be to utilize %SIG{ALARM} to print some indicator at a specified time. This is what I ended up doing.
CODE
#!/usr/bin/perl
use strict;
use warnings;
package bh::image;
sub get_valid_images {
die "Incorrect number of arguments passed to get_valid_images.\n" un
+less @_== 1;
my $dir = shift;
my $pre = $dir;
# get list of possible images.
opendir(DIR, $dir) or die "Can't opendir $dir: $!\n";
my @tmp = grep { /\.jpg$/i or
/\.jpeg$/i or
/\.gif$/i or
/\.png$/i } readdir(DIR);
closedir(DIR);
# make sure files are valid
my @images;
require Image::Info;
foreach my $a (@tmp) {
# is file readable?
next unless ( -r "$dir/$a" );
# can we parse meta info from file?
my $info = Image::Info::image_info("$dir/$a");
push @images, "$pre/$a" unless $info->{error};
}
return @images;
}
package bh::email;
sub email_images {
die "Incorrect number of arguments passed to get_valid_images.\n" un
+less @_== 3;
my ( $hdr, $smtp, $imgs ) = @_;
require MIME::Lite;
my $msg = MIME::Lite->new(
From => $hdr->{from},
To => $hdr->{to},
Subject => $hdr->{subj},
Data => $hdr->{body},
Type => 'text'
);
foreach my $item ( @$imgs ) {
$msg->attach( Path => $item,
Type => 'image/jpeg',
);
}
pop_first($smtp->{pop3},$smtp->{pop3user},$smtp->{pop3pass}) if $smt
+p->{popfirst};
$msg->send('smtp', $smtp->{smtp});
return 1;
}
sub pop_first {
die "Incorrect number of arguments passed to get_valid_images.\n" un
+less @_== 3;
my ($srvr,$user,$pass) = @_;
require Net::POP3;
my $pop = Net::POP3->new($srvr);
if ($pop->login($user,$pass)) {
my $msgnums = $pop->list;
return 1;
}else{
return undef;
}
}
package main;
my $time = 5;
local $SIG{ALRM} = sub { print '.'; alarm $time; };
$|=1; # turn off buffering.
alarm $time;
my @images = bh::image::get_valid_images('.');
my $hdr = { from => 'test@test.com',
to => 'test@test.com',
subj => 'Test message',
body => "Here is the test message body.\n\n\ntester\n" };
my $srvr = { smtp => 'smtp.test.net',
popfirst => 1,
pop3 => 'pop3.test.net',
pop3user => 'test',
pop3pass => 'test' };
bh::email::email_images ( $hdr, $srvr, \@images ) or die "Error sendin
+g email message.\n";
alarm 0;
I am sure this is a common problem. How do you approach this problem?
Thanks for any suggestions... or any code review suggestions. :)
zzSPECTREz