jwood_70 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
You can pretty much call me a Perl noob but I've had a go at least so please be gentle.
I’ve had a request to create a script to do a mass email to our clients (3k+) with data in individual files. The client email address will be in the first line of the file, subject in the second line and individual data in the rest of the file. Data format is csv and files will have a .csv extention. What I’ve written so far is:
#!/usr/bin/perl -w $dir="/home/jwood/files"; opendir (JDE,$dir) or die "Cannot open $dir: $!"; while ( defined ($file = readdir JDE) ) { next if $file =~ /^\.\.?$/; my $filename = "$dir/$file"; print "$filename\n"; open CFILE, "$filename" or die "Cannot open $file: $!"; $line = <CFILE>; chomp($line); $address = $line; $line = <CFILE>; chomp($line); $subject = $line; print "mail -s \"$subject\" $address\n"; `/usr/bin/mail -s "$subject" $address < $filename`; close(CFILE); } closedir(JDE);
While I’m sure this is pretty poor compared to what you guys can do, it mostly works but it doesn’t have the subject in the emails.
The other thing that I need to add to this is getting some text into the email and having the csv file as an attachment. This text would be the same for all emails.
Any tips, upgrades, etc would be much appreciated.

Replies are listed 'Best First'.
Re: File processing/email program
by GrandFather (Saint) on Oct 23, 2007 at 02:51 UTC

    You may find that MIME::Lite or one of the other email managing modules generates fewer surprises than using system commands to do the work. Consider:

    # Create the message $msg = MIME::Lite->new( From =>'me@myhost.com', To => $address, Subject => $subject, Type => 'multipart/mixed' ); # Add the text message part: $msg->attach(Type =>'TEXT', Data =>"Here's the GIF file you wanted" ); # Add the file part: $msg->attach(Type =>'TEXT', Path => $filename, Disposition => 'attachment' ); $msg->send ();

    Perl is environmentally friendly - it saves trees
      Thanks for that tip. It works a treat. Took me ages to get it installed with all pre-reqs and finally found it easier to to install Perl & GCC from Sunfreeware than using the default Solaris Perl.
Re: File processing/email program
by toolic (Bishop) on Oct 23, 2007 at 02:55 UTC
    Welcome to the Monastery.

    There is a wealth of great code available on CPAN. A quick search reveals the Mail::Header module, which might help you in parsing email headers.

    Another good resource is the Perl documentation. Searching for "mail" yields a number of potentially handy links.

    It is also a good practice to use strict; at the top of your code to help enforce good coding style.

Re: File processing/email program
by Krambambuli (Curate) on Oct 23, 2007 at 08:24 UTC