Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to a Gmail inbox

Tags:

gmail

perl

imap

I am currently trying to connect to a gmail inbox using Perl and Net::IMAP::Client with the following code

use strict;
use warnings;

use Net::IMAP::Client;

my $user = '[address]@gmail.com';
my $pwd = '[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)

But the $imap variable is undef and I am getting this error:

Use of uninitialized value $_ in concatenation (.) or string at testIMAP.pl line 9.
Could not connect to IMAP server: at testIMAP.pl line 9.

I have successfully connected to the mailbox using Outlook, but as I'm not getting an error message I'm not sure where to look. Does anyone know what I'm doing wrong here?

like image 394
Gnippots Avatar asked Mar 30 '17 01:03

Gnippots


1 Answers

A big thanks to zdim for help troubleshooting.

Firstly, zdim pointed out that I had the incorrect error variable. $_ should have been $!

This revealed the error message "Network is unreachable", however I was able to pint and telnet to 'imap.gmail.com' successfully.

The solution to this was found here Perl IO::Socket::SSL: connect: Network is unreachable .

Changing the use statement in the Net::IMAP::Client module to the following worked:

use IO::Socket::SSL 'inet4';

After this, the connection was established, but the login would fail with

Login failed: [ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)

This is due to Gmail's security features. I received an email that allowed me to confirm that the connection was not malicious, and then subsequent logins were successful.

For others, there may be a few solutions to this last one. You may need to issue an 'app password' If two-step authentication is activated, or you might need to toggle on 'allow less secure apps'

like image 137
Gnippots Avatar answered Sep 20 '22 07:09

Gnippots