Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I connect to gmail from perl?

Tags:

email

perl

imap

I am trying to read messages from a gmail account, and the examples I've seen aren't working.

I started with this:

use Mail::IMAPClient;
use IO::Socket::SSL;

my $user = 'user\@mydomain.com';
my $pwd = 'password';

my $socket = IO::Socket::SSL->new(
    PeerAddr => 'imap.gmail.com',
    PeerPort => 993,
    SSL_verify_mode => SSL_VERIFY_PEER,
    )
    or die "socket(): $@";

my $client = Mail::IMAPClient->new(
    Socket => $socket,
    User     => $user,
    Password => $pwd,
    )
    or die "new(): $@";

if ( $client->IsAuthenticated() ) {
    print "Auth OK\n";
} else {
    print "No auth\n";
}

This appears to work, but never authenticates. According to the documentation, Mail::IMAPClient->new should call login if username and password are provided.

I have tried calling client->login with no difference.

There are a few questions with similar content, but the answers state to use a different package (Mail::Webmail::Gmail is one, but it seems obsolete and doesn't work either)

The account is a google apps account, not a regular gmail account. I have enabled imap access for the account.

I also tried using Net::IMAP::Client, both with a google apps account and using my gmail account with an app-specific password, and get nothing but "Invalid credentials".

use Net::IMAP::Client;

my $user = 'user\@gmail.com';
my $pwd = ' app password';

my $imap = Net::IMAP::Client->new(
    server => 'imap.gmail.com',
    user   => $user,
    pass   => $pwd,
    ssl    => 1,                              # (use SSL? default no)
    ssl_verify_peer => 0,                     # (use ca to verify server, default yes)
    port   => 993                             # (but defaults are sane)
    ) or die "Could not connect to IMAP server: $_";

$imap->login or
    die('Login failed: ' . $imap->last_error);

Is there something I'm missing when trying to connect to gmail imap?

like image 498
chris Avatar asked Mar 20 '23 10:03

chris


1 Answers

In Perl, the string "\@" inside single quotes is literally "\@".

Lose the \.

like image 183
mob Avatar answered Mar 28 '23 04:03

mob