Perl Logo

We talked about some of the benefits of setting up an email server in Linux and how you can use python to send email. Now we are going to look at how you can send email from Perl.

The Code

use Net::SMTP::TLS;
my $mailer = new Net::SMTP::TLS(
	'smtp.gmail.com',
	Hello   =>      'smtp.gmail.com',
	Port    =>      587,
	User    =>      'username',
	Password=>      'password');
$mailer->mail('from@domain.com');
$mailer->to('to@domain.com');
$mailer->data;
$mailer->datasend("Sent from perl!");
$mailer->dataend;
$mailer->quit;

Subscribe via Email

Subscribe to Nixtutor via Email

Enter your email address:

Was this information useful?

3 Responses

  1. Leon Brocard

    7-7-2009

    Or, you could use the module on CPAN which does this for you and makes it easy to create emails too: Email::Send::Gmail

    http://search.cpan.org/dist/Email-Send-Gmail/

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Email::Send;
    use Email::Send::Gmail;
    use Email::Simple::Creator;

    my $email = Email::Simple->create(
    header => [
    From => 'magic_monitoring@gmail.com',
    To => 'acme@astray.com',
    Subject => 'Server down',
    ],
    body => ‘The server is down. Start panicing.’,
    );

    my $sender = Email::Send->new(
    { mailer => ‘Gmail’,
    mailer_args => [
    username => 'magic_monitoring@gmail.com',
    password => 'XXX',
    ]
    }
    );
    eval { $sender->send($email) };
    die “Error sending email: $@” if $@;

  2. Mark Sanborn

    7-7-2009

    You gotta love cpan :)

  3. Sawyer

    7-12-2009

    I like to use Email::Stuff for email handling. It uses Email::Send in the backend and I can just write it as so: ) (hope the aligning looks right)
    Email::Stuff->from ($from )
    ->to ($to )
    ->subject ($subject)
    ->text_body ( $text )
    ->using( ‘Gmail’, username => $user, password => $pass )
    ->send;

    However, Email::Send::Gmail doesn’t play nice with Email::Stuff. Specifically the subroutine get_env_sender(). So, to fix it, I add the following line to my code prior to sending the email:
    local *Email::Send::Gmail::get_env_sender = sub { };