FAQ 9.20 How do I send mail?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq9.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


9.20: How do I send mail?

    Use the "sendmail" program directly:

            open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
                    or die "Can't fork for sendmail: $!\n";
            print SENDMAIL <<"EOF";
            Subject: A relevant subject line

            Body of the message goes here after the blank line
            in as many lines as you like.
            close(SENDMAIL)     or warn "sendmail didn't close nicely";

    The -oi option prevents sendmail from interpreting a line consisting of
    a single dot as "end of message". The -t option says to use the headers
    to decide who to send the message to, and -odq says to put the message
    into the queue. This last option means your message won't be immediately
    delivered, so leave it out if you want immediate delivery.

    Alternate, less convenient approaches include calling mail (sometimes
    called mailx) directly or simply opening up port 25 have having an
    intimate conversation between just you and the remote SMTP daemon,
    probably sendmail.

    Or you might be able use the CPAN module Mail::Mailer:

            use Mail::Mailer;

            $mailer = Mail::Mailer->new();
            $mailer->open({ From    => $from_address,
                                            To      => $to_address,
                                            Subject => $subject,
                    or die "Can't open: $!\n";
            print $mailer $body;

    The Mail::Internet module uses Net::SMTP which is less Unix-centric than
    Mail::Mailer, but less reliable. Avoid raw SMTP commands. There are many
    reasons to use a mail transport agent like sendmail. These include
    queuing, MX records, and security.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline