perl imap move message to trash (Mail::IMAPClient)

2019-03-31 12:45发布

问题:

I need to move all messages from unseen to the trash(and delete then from inbox).

my $inbox = $imap->select("Inbox");
my @mails = ( $imap->unseen );

foreach my $msgid (@mails) {
    $imap->set_flag( "Deleted", @mails )
        or die "Could not set flag: $@\n";
}

This code delete messages completely. (without expunge too)

I tried to use "move" and "copy":

my $Trash = "Trash";
my $newUid = $imap->move( $Trash, $msgid )
    or die "Could not move: $@\n";
my $uidList = $imap->copy( $Trash, @mails )
    or die "Could not copy: $@\n";

But "move" create new mark(folder) and "copy" dont work "Could not copy: 6 NO [TRYCREATE] No folder Trash (Failure)" I tried to use name: /Trash, [imap]Trash etc., similar results. This must work for different mail services!

i use Mail::IMAPClient

回答1:

Try the code below for imap servers supporting RFC6154 like Gmail. It should detect Trash folder name.

use  Mail::IMAPClient; 
 ......
my $Trash;
{
  my @Trash;
  my @fhashes = $imap->folders_hash or die "Could not get list of folder hashes.\n";
  foreach my $fhash (@fhashes) {
    next unless map { /^\\Trash$/ ? ($_) : () } @{$fhash->{attrs}};
    push (@Trash, $fhash->{name});
  }
  $Trash = pop( @Trash) if @Trash == 1;
}
if( defined( $Trash)) {
   ...
}   


标签: perl email imap