How can I send the content of file as email in Perl?

10,643

Solution 1

You can just slurp up the contents of the file like so and use it as you would any other string:

 open my $fh, '<', 'file.txt' or die "Ouch: $!\n";

 my $text = do {
   local $/;
   <$fh>
 };

 close $fh or die "Ugh: $!\n";
 print $text,"\n";

Solution 2

I use MIME::Lite, this is the cron script I use for my nightly backups:

$msg = MIME::Lite->new(
  From    => '[email protected]',
  To      => '[email protected]',
  Bcc     => '[email protected]',
  Subject => "DB.tgz Nightly MySQL backup!",
  Type    => "text/plain",
  Data    => "Your backup sir.");

$msg->attach(Type=> "application/x-tar",
             Path =>"/var/some/folder/DB_Dump/DB.tgz",
             Filename =>"DB.tgz");

$msg->send;

Solution 3

What are you using to send the email? I use MIME::Lite. and you can use that to just attach the file.

Otherwise you'd just open the log, read it in line at a time (or use File::Slurp) and dump the contents of the file into the email.

Share:
10,643
codingbear
Author by

codingbear

I design, I code, I test

Updated on August 01, 2022

Comments

  • codingbear
    codingbear over 1 year

    I have a log that gets created from a bunch of cron jobs. My task now is to send specific logs (e.g. error outputs) as an email. What is the best way to get content from a file and send it as an email?

    I have already figured out how to send email in perl. I just need to figure out how to read in the file and put it as the text of the email.

  • codingbear
    codingbear over 14 years
    I think this is the way I was looking for. Can you explain the "my $text = do { ... };"? I'm really new to perl.
  • M.Sworna Vidhya
    M.Sworna Vidhya over 14 years
    The block following 'do' is executed and the last line is returned (see perldoc -f do). The local $/ undefines the value of the input record separator so <$fh> gets the entire file. This is a fairly common perl idiom called file slurping. You could also use File::Slurp::read_file as Sinan recommended.
  • silbana
    silbana over 14 years
    @bLee if you are new to Perl, you should read the entire Perl documentation at least once. Type perldoc perltoc to get the list of contents. perldoc perldoc for information on perldoc.
  • codingbear
    codingbear over 14 years
    @Sinan: I'm so new that I didn't even know such thing (perldoc) exists. Thanks!
  • codingbear
    codingbear over 14 years
    Great example, but I didn't want the file attachment. +1
  • codingbear
    codingbear over 14 years
    Just for clarification: there is a missing ; after <$fh> inside the do statement.
  • M.Sworna Vidhya
    M.Sworna Vidhya over 14 years
    @bLee: perl doesn't need a semi-colon to end the last statement in the block.
  • visual_learner
    visual_learner over 14 years
    +1 to Sinan - perldoc is an exceptionally well-written and comprehensive piece of documentation.