(perl Net::SMTP) authentication failure using gmai

2019-05-26 06:54发布

问题:

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.

回答1:

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



回答2:

Gmail uses TLS/STARTTLS on port 587, SSL on port 465. Please follow Sending email through Google SMTP from Perl. Alternatively you could use Email::Send::SMTP::Gmail. I recommend this as it is way easier to use and has many more features.



标签: perl smtp gmail