Using a global variable as parameter to Mail::IMAP

2019-06-03 17:14发布

问题:

I'm trying to make a mail bulk downloader with perl, that will connect on multiple accounts and download it´s attachments, but i´m still learning this language. I´m having an issue with credentials stored in a text file reading. Whenever i pass the parameters as string, i can connect to my account and retrieve information about unread emails. Snippet:

my $imap = Mail::IMAPClient->new(
  Server   => 'mail.example.com',
  User     => 'nicolas',
  Password => 'password',
  Uid      => 1,
) or die "Erro ao conectar na conta";

It connects, and using my @mails = ($imap->unseen); with a foreach loop i can get all my unseen mails on a list.

However, if i try to get my credentials from a file and assign to a variable and further use this variable as credentials to $imap it fails:

foreach my $line ( @lines ) {
  my @credentials = split( /\s+/, $line );
  my $domain = $credentials[0];
  my $account = $credentials[1];
  my $password = $credentials[2];

my $imap = Mail::IMAPClient->new(
  Server   => 'mail.example.com',
  User     => $account,
  Password => $password,
  Uid      => 1,) 
}

When i run the script i get this message:

$ ./folder_list.pl
Can't call method "select" on an undefined value at ./folder_list.pl line 43.

If i print "$account", "$password"; i can check its values, but cant use them as parameters of $imap. What am i missing here?

回答1:

I suspect that there's an empty line at end your file. This loop you have in question loops over all lines and file, remembers only last one and then constructs IMAPClient with that data. If you construct it with empty account/password you are likely to get errors like those you've mentioned.

Drop our and use my and move processing into the loop to, because I understand that's exactly what you want - do IMAP processing with every account.

foreach my $line ( @lines ) {
    my @credentials = split( /\s+/, $line );
    my  $domain = $credentials[0];
    my  $account = $credentials[1];
    my  $password = $credentials[2];

    my $imap = Mail::IMAPClient->new(
        Server   => 'mail.example.com',
        User     => $account,
        Password => $password,
        Uid      => 1,
    )

    # Rest of code for each mailbox
    # ....
}


回答2:

Weird. Problem solved on el5(CentOS) after upgrading perl to pel-5.8.8-43.el5_11 and the libs to perl-Mail-IMAPClient-3.37-1.el5 and perl-Email-MIME-1.903-2.el5.rf. Don´t know witch of them was causing the problem but, it solved.

Code still the same:

  # Faz a conexão com a conta. Se não der certo passa pra próxima
  my $imap = Mail::IMAPClient->new(
    Server   => $mailserver,
    User     => $account,
    Password => $password,
    Uid      => 1) or ($log_script->log("$hora: Erro de autenticação na conta $account. Verifique as credenciais") and next);


标签: perl imap