Question

I have never played with fetching and moving emails before using IMAP and PHP, so im struggeling with moving emails that are sent to the trash back to the inbox.

Ok, so i'm fetching my emails from Gmail correctly, and i am able to delete them, or move them to trash rather.

When i try to move them back to Inbox i get the following error:

Notice: Unknown: [TRYCREATE] No folder [Gmail]/Inbox (Failure) (errflg=2) in Unknown on line 0

So obviously there is something i dont quite get, and i have been searching the web and stackoverflow for the answer the last couple of hours with no luck. Does anyone know why this particular action does not succeed?

Any help is as usual much appreciated, i would love to get the hang of this and make myself a little email app.

Below is the class i have made, see the method undo(), thats where this particular warning pops up.

class Gmail {

public $emailsexists = false;
public $emailarray = '';

private $username;
private $password;
private $inbox;


public function __construct($username,$password) {
    /* connect to gmail using imap */
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    $this->username = $username;
    $this->password = $password;
    /* try to connect using username and password set in core/init.php (gmail_credentials) */
    $this->inbox = imap_open($hostname,$this->username,$this->password) or die('Cannot connect to Gmail: ' . imap_last_error());
}

public function delete($email) {
    if ($email !== '' && is_numeric($email)) {
        if (imap_mail_move($this->inbox, $email, '[Gmail]/Trash')) {
            return true;
         } else {
            return false;
         }
    } else {
        return false;
    }
    imap_close($this->inbox);
}

public function undo($email) {
    if ($email !== '' && is_numeric($email)) {
        if (imap_mail_move($this->inbox, $email, '[Gmail]/Inbox')) { // FIX Throws back a warning
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
    imap_close($this->inbox);
}

public function unseen($number = false) {

    /* grab emails */
    $emails = imap_search($this->inbox,'UNSEEN');
    /* if emails are returned, cycle through each... */
    if($emails) {
        /* statement that tells that emails exist */
        $this->emailsexists = true;
        /* put the newest emails on top */
        rsort($emails);
        /* Start the counter */
        $x = 0;
        /* Open up the accordion */
        $this->emailarray.= '<div id="accordion">';
        /* for every email... */
        foreach($emails as $email) {
            /* get information specific to this email */
            $overview = imap_fetch_overview($this->inbox,$email,0);
            $structure = imap_fetchstructure($this->inbox, $email);
            $message = imap_fetchbody($this->inbox,$email,1,FT_PEEK);
            if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
                $part = $structure->parts[1];
                $message = imap_fetchbody($this->inbox,$email,2,FT_PEEK);

            }
            /* escape and decode the mimeheaders */
            $subject = escape(str_replace("_"," ", mb_decode_mimeheader($overview[0]->subject)));
            /* decode and put the subject into the accordion header */
            $this->emailarray.= '<h3>'.html_entity_decode(escape($subject)).'</h3>';
            $this->emailarray.= '<div>';
            $this->emailarray.= '<div class="btn-group pull-right">';
            $this->emailarray.= '<a href="#" title="Reply" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-share-alt text-success"></span></a>';
            $this->emailarray.= '<a href="#" title="Forward" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-send text-success"></span></a>';
            $this->emailarray.= '<a href="index.php?task=delete&id='.$email.'" title="Delete" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-fire text-danger"></span></a>';
            $this->emailarray.= '</div>';
            $this->emailarray.= '<p>';
            /* decode the email body using the built in quoted_printable_decode function */
            $this->emailarray.= quoted_printable_decode($message);
            $this->emailarray.= '</p>';
            $this->emailarray.= '</div>';

            /* if the counter reaches a certain number, break out and continue the script */
            $x++;
            if ($number) {
                if ($x >= $number) {
                    break;
                }
            }

        }
        /* close off the accordion */
        $this->emailarray.= '</div>';


    /* If no emails are found return a message */
    } else {
        echo "No emails";
    }
    /* close the imap connection */
    imap_close($this->inbox);
}

}
Was it helpful?

Solution

I found that if i connect to the Trash and then use an asterix to get the last message it works as intended.

public function undo($email) {
    // check if message id exists and is numeric
    if ($email !== '' && is_numeric($email)) {
        // set hostname to trash
        $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Trash';
        $this->inbox = imap_open($hostname,$this->username,$this->password) or die('Cannot connect to Gmail: ' . imap_last_error());
        // return true if the message was moved
        if (imap_mail_move($this->inbox, '*', 'Inbox')) {
        return true;
        } else {
        return false;
        }
    } else {
    return false;
    }
    imap_close($this->inbox,CL_EXPUNGE);
}

OTHER TIPS

Move mail INBOX To TRASH THROUGH IMAP using node-imap.

const Imap = require("imap");
const mailBox = new Imap({
        host: "imap.gmail.com",
        password: "password",
        port: 993,
        user: "email",
        tls: true,
        connTimeout: 30000,
        authTimeout: 30000,
        keepalive: false,
        tlsOptions: {
          rejectUnauthorized: false,
        },
      });
  
  mailBox.once("error", console.error);
  mailBox.once("ready", () => {
    mailBox.openBox("INBOX", false, (error, box) => {
      if (error) throw error;
  
      mailBox.search(
        [
          // "UNSEEN",
          ["SUBJECT", "When to say 'sorry' at work"],
          ["FROM", "taco@trello.com"]
        ],
        (error, results) => {
          if (error) throw error;
          console.log("results",results);
          for (const uid of results) {
            
            const mails = mailBox.fetch(uid, {
              bodies: ""
              // markSeen: true
            });
            mails.once("end", () => mailBox.end());
  
            mails.on("message", (message, seq) => {
              console.log('message',message);
              message.on("body", stream => {
                console.log("results123456--------",uid);
                let buffer = "";
                stream.on("data", chunk => (buffer += chunk.toString("utf8")));
                stream.once("end", () => mailBox.move(uid, "[Gmail]/Trash")); 
              });
            });
          }
        }
      );
    });
  });
  
  mailBox.connect();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top