如何连接到 Gmail 收件箱

How to connect to a Gmail inbox

我目前正在尝试使用 Perl 连接到 gmail 收件箱,并且 Net::IMAP::Client 使用以下代码

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)

但是 $imap 变量是 undef,我得到这个错误:

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

我已使用 Outlook 成功连接到邮箱,但由于没有收到错误消息,我不确定去哪里查看。有谁知道我在这里做错了什么?

非常感谢 zdim 帮助解决问题。

首先,zdim 指出我的错误变量不正确。 $_ 应该是 $!

这显示了错误消息 "Network is unreachable",但是我能够成功地 pint 和 telnet 到 'imap.gmail.com'。

在此处找到了此问题的解决方案 Perl IO::Socket::SSL: connect: Network is unreachable

将 Net::IMAP::Client 模块中的 use 语句更改为以下有效:

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

此后连接建立,但登录失败

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

这是因为 Gmail 的安全功能。我收到一封电子邮件,让我确认连接不是恶意的,然后后续登录成功。

对于其他人,最后一个可能有一些解决方案。如果激活了两步验证,您可能需要发出 'app password',或者您可能需要打开 'allow less secure apps'