Perl – (perl Net::SMTP) authentication failure using gmail smtp server

gmailperlsmtp

I have written a perl script to send email using the gmail's smtp server: smtp.gmail.com –

use Net::SMTP;

my $smtp = Net::SMTP->new('smtp.gmail.com',
                    Port=> 587,
                    Timeout => 20,
                    Hello=>'user@gmail.com'
                    );
print $smtp->domain,"\n";
$sender = "user@gmail.com";
$password = "mypassword";
$smtp->auth ( $sender, $password ) or die "could not authenticate\n";
$receiver = "user@gmail.com";

$subject = "my custom subject";
$smtp->mail($sender);
$smtp->to($receiver);
$smtp->data();
$smtp->datasend("To: <$reciever> \n");
$smtp->datasend("From: <$sender> \n");
$smtp->datasend("Content-Type: text/html \n");
$smtp->datasend("Subject: $subject");
$smtp->datasend("\n");
$smtp->datasend('the body of the email');
$smtp->dataend();
$smtp->quit();
print "done\n\n";

For 'user', I have my gmail username and for 'mypassword' I have the password. But when I run this code it stops at the auth itself giving : could not authenticate.

I am able to connect to the smtp serever of google as I get : 'mx.google.com' as the result of :
print $smtp->domain,"\n";

What is it that I am doing wrong? Please help.

Best Answer

use Net::SMTP;
my $smtp = Net::SMTP->new ....

afaik you need to use an encrypted connection to send via gmail, use Net::SMTP::TLS or Net::SMTP::SSL (with port 465)

Hello=>'user@gmail.com'

'Hello' is not an email address, put your hostname there instead

$sender = "user@gmail.com";
...
$receiver = "user@gmail.com";

put these in single quotes

if you still get "could not authenticate." make sure you have the modules MIME::Base64 and Authen::SASL installed.

 $smtp->datasend("To: <$reciever> \n");

should be $receiver, not $reciever

Related Topic