tags:

views:

116

answers:

4

I am trying to send an HTML email using Perl.

 open(MAIL,"|/usr/sbin/sendmail -t");

    ## Mail Header
    print MAIL "To: $to\n";
    print MAIL "From: $from\n";
    print MAIL "Subject: $subject\n\n";
    ## Mail Body
    print MAIL "Content-Type: text/html; charset=ISO-8859-1\n\n"
        . "<html><head></head><body>@emailBody";
 close(MAIL)

Is that the correct way of doing it? It is not working for some reason. Thanks for your help.

+4  A: 

The content type should be part of the mail header. Right now it's part of the mail body. The header is separated from the body by a double newline. So, removing the second newline after the subject header should fix the problem of content type not being correctly interpreted.

BalusC
+2  A: 

You should not really talk to sendmail directly via a pipe, uinstead use a peoper CPAN module.

Email::Sender is an example.

Mail::Sender has a specific guide on sending HTML messages

DVK
+7  A: 

Start with Email::Sender::Simple or Email::Sender.
There is a quickstart guide in CPAN, and Ricardo wrote a good use-me in his 2009 advent calendar

From the quickstart guide:

  use strict;
  use Email::Sender::Simple qw(sendmail);
  use Email::Simple;
  use Email::Simple::Creator;

  my $email = Email::Simple->create(
    header => [
      To      => '"Xavier Q. Ample" <[email protected]>',
      From    => '"Bob Fishman" <[email protected]>',
      Subject => "don't forget to *enjoy the sauce*",
    ],
    body => "This message is short, but at least it's cheap.\n",
  );
  sendmail($email);
spazm
+1 for an excellent post. I in-lined the URLs for you ..
lexu
A: 

If you are just generating spewy emails and you don't need massive robustness or tweaking, you could always just take the shortcut way...

use Email::Stuff;

my $html = <<'END_HTML';
<html>
  ...
</html>
END_HTML

Email::Stuff->to('"Xavier Q. Ample" <[email protected]>')
            ->from('"Bob Fishman" <[email protected]>')
            ->subject("Don't forget to *enjoy the sauce*")
            ->html_body($body)
            ->send;