简体   繁体   中英

How do I send multi-line output from Perl to /bin/mail?

I have a Perl script that prints multiple lines of output to screen. I need to capture those lines and either pipe them into a single piece of email ( /bin/mail ) or into a text file that I can send by /bin mail in another operation. Actually, I have already figured out the easy (dumb) way whereby I use a bash wrapper to do the mailing bit. Looks like,

#!/usr/bin/bash
source /nethome/zog/.bash_profile 
cd /nethome/zog/bin/perl  
/nethome/zog/bin/perl/find_free_space.pl > text.file
/bin/mail -s FreeSpace@NJ3 zog@geemail.com < text.file

I want to be using Net::SMTP to do the smtp bit. The above is inelegant, to say the least.

I saw something like this:

open(MAIL, "| /bin/mail -s FreePorts me\@geemail.com") || 
   die "mail failed: $!\n"; print MAIL "This is how it goes."

on stackoverflow but failed to redirect the STDOUT into mail. I'm using:

$complete_output .= "\n"; "|/bin/mail -s FreePorts zog\@geeemail.com" || die "mail failed: $!\n";

I'm not sure if you all need to see the Perl script in order to help, but it is on pastebin . Please let me know.

STDOUT isn't in play here. Is there something you forgot to tell us? What happened when you printed to the MAIL filehandle? Did that output make it into the message? What happens when you send multiple lines to the MAIL filehandle?

Your code is:

"|/bin/mail -s FreePorts zog\@geeemail.com" || die "mail failed: $!\n";

That does nothing. It's a string, which is also a true value. The alternation never does to the die branch. What happened when you used the first bit of code in your question? Write a small example script to see if you can send mail and test with that until you figure it out. For example, this is a complete script that tests your problem:

#!perl
use strict;
use warnings;
open my $mail, '| /bin/mail -s FreePorts me@geemail.com';
print $mail "This is a test message from $$ at " . localtime() . "\n";
close $mail or die "The pipe failed!\n $?";

What happens when you run that? What happens when you try that same command from the command line?

Why not use a Perl module (like one of the Email::* modules) instead of relying on an external command? There's a lot to know about interprocess communication, and I think you're behind the curve on that. A module takes care of all of the details for you, has a nicer interface, and is more flexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM