2

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.

CuriousSid
  • 534
  • 3
  • 11
  • 25

2 Answers2

3
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

Gryphius
  • 75,626
  • 6
  • 48
  • 54
  • I dropped the 'Hello' argument and corrected the quote mistakes, still no result. The TLS and SSL modules are available for perl 5.14 windows. I can't use it as I have to use win32::serialport as well in windows. Please tell some way to send it by tweaking the above code itself. – CuriousSid Jun 13 '12 at 09:15
  • +1 for mentioning "if you still get "could not authenticate." make sure you have the modules MIME::Base64 and Authen::SASL installed." – aloha Aug 29 '13 at 11:50
0

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.

daxim
  • 39,270
  • 4
  • 65
  • 132
user1092042
  • 1,297
  • 5
  • 24
  • 44
  • I have to use win32::serialport as well which is unsupported in perl 5.14 in windows. The one you are referring is supported only for 5.14 in windows. – CuriousSid Jun 13 '12 at 09:01