Question

I'm trying to set some email headers when sending email in perl. I have the following code, however the Content-Type and X-Priority get sent in the body of the message. The following is my code.

my $sendmail = "| /usr/sbin/sendmail -t";

open(MAIL,$sendmail)
        or die("Unable to open sendmail.  $!");
print MAIL "Reply-to: $reply\n";
print MAIL "From: $from\n";
print MAIL "To: $to\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Content-Type: text/plain\n";
print MAIL "X-Priority: 1\n";
print MAIL "blah\n";
print MAIL "$link\n\n";
close(MAIL);

I'm using sendmail as I'd like something out of the box without having to bother to install anything additional.

Was it helpful?

Solution

Remove second "\n" from the line below. Sendmail treat first empty line as "end of headers".

print MAIL "Subject: $subject\n\n";

Additional fixes:

  • add -i command line options to avoid special treatment of lines starting with dot
  • specify recipients as command line arguments passed to sendmail after -- command line option
  • check sendmail exit code as returned by close
  • use single print with "here document"

print MAIL <<"END_OF_MESSAGE";
Reply-to: $reply
From: $from
To: $to
Subject: $subject
X-Priority: 1

blah blah blah
$link
END_OF_MESSAGE

OTHER TIPS

Your actual error is that you put \n\n after the subject. That ends the header and starts the body.

You really should use Net::SMTP which comes with almost all Perl distributions. This way, you're not dependent upon the behavior of sendmail.

The Net::SMTP module is fairly simple to use too. A lot of people don't like it because it's a bit too close to the raw protocol. A lot of people prefer something like Mail::Sendmail, but that's not part of Perl's standard distribution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top