function move($msg_index, $folder = 'INBOX.Processed') { // move on server imap_mail_move($this->conn, $msg_index, $folder); imap_expunge($this->conn); // re-read the inbox $this->inbox(); }
function move($uid, $folder) { $tries = 0; while ($tries++ < 3) { if (imap_mail_move($this->stream, $uid, $folder, CP_UID)) { imap_expunge($this->stream); return true; } else { sleep(1); } } return false; }
/** * verschiebt die Nachricht mit der gegebenen uid in die gegebene Mailbox *auf dem selben Server* * @param integer $uid * @param string $dest_mbox * @return boolean */ public function imapMailMove($uid, $dest_mbox) { if ($this->imap === null) { throw new IMAPException(__METHOD__ . ' not connected'); } $this->imapPing(true); /* * dont't add the server part, * only the mailbox name works fine * * $dest_mbox = $this->server.$dest_mbox; */ return imap_mail_move($this->imap, $uid, $dest_mbox, CP_UID); }
/** * @param $mail_id * @param string $folder */ public function moveMailToFolder($mail_id, $folder = 'INBOX/Junk') { $imapresult = imap_mail_move($this->getImapStream(), $mail_id, $folder, CP_UID); if (!$imapresult) { echo imap_last_error(); } }
public function moveMail($mailId) { $imapresult = imap_mail_move($this->getImapStream(), $mailId, 'INBOX.Archive') && $this->expungeDeletedMails(); if ($imapresult == false) { error_log(imap_last_error()); } return $imapresult; }
/** * Process the messages in a mailbox * * @param string $max maximum limit messages processed in one batch, if not given uses the property $maxMessages * * @return boolean */ public function processMailbox($max = false) { if (empty($this->actionFunction) || !is_callable($this->actionFunction)) { $this->errorMessage = 'Action function not found!'; $this->output(); return false; } if ($this->moveHard && $this->disableDelete === false) { $this->disableDelete = true; } if (!empty($max)) { $this->maxMessages = $max; } // initialize counters $totalCount = imap_num_msg($this->mailboxLink); $fetchedCount = $totalCount; $processedCount = 0; $unprocessedCount = 0; $deletedCount = 0; $movedCount = 0; $this->output('Total: ' . $totalCount . ' messages '); // proccess maximum number of messages if ($fetchedCount > $this->maxMessages) { $fetchedCount = $this->maxMessages; $this->output('Processing first ' . $fetchedCount . ' messages '); } if ($this->testMode) { $this->output('Running in test mode, not deleting messages from mailbox<br />'); } else { if ($this->disableDelete) { if ($this->moveHard) { $this->output('Running in move mode<br />'); } else { $this->output('Running in disableDelete mode, not deleting messages from mailbox<br />'); } } else { $this->output('Processed messages will be deleted from mailbox<br />'); } } for ($x = 1; $x <= $fetchedCount; $x++) { /* $this->output($x . ":", self::VERBOSE_REPORT); if ($x % 10 == 0) { $this->output('.', self::VERBOSE_SIMPLE); } */ // fetch the messages one at a time if ($this->useFetchstructure) { $structure = imap_fetchstructure($this->mailboxLink, $x); if ($structure->type == 1 && $structure->ifsubtype && $structure->subtype == 'REPORT' && $structure->ifparameters && $this->isParameter($structure->parameters, 'REPORT-TYPE', 'delivery-status')) { $processed = $this->processBounce($x, 'DSN', $totalCount); } else { // not standard DSN msg $this->output('Msg #' . $x . ' is not a standard DSN message', self::VERBOSE_REPORT); if ($this->debugBodyRule) { if ($structure->ifdescription) { $this->output(" Content-Type : {$structure->description}", self::VERBOSE_DEBUG); } else { $this->output(" Content-Type : unsupported", self::VERBOSE_DEBUG); } } $processed = $this->processBounce($x, 'BODY', $totalCount); } } else { $header = imap_fetchheader($this->mailboxLink, $x); // Could be multi-line, if the new line begins with SPACE or HTAB if (preg_match("/Content-Type:((?:[^\n]|\n[\t ])+)(?:\n[^\t ]|\$)/is", $header, $match)) { if (preg_match("/multipart\\/report/is", $match[1]) && preg_match("/report-type=[\"']?delivery-status[\"']?/is", $match[1])) { // standard DSN msg $processed = $this->processBounce($x, 'DSN', $totalCount); } else { // not standard DSN msg $this->output('Msg #' . $x . ' is not a standard DSN message', self::VERBOSE_REPORT); if ($this->debugBodyRule) { $this->output(" Content-Type : {$match[1]}", self::VERBOSE_DEBUG); } $processed = $this->processBounce($x, 'BODY', $totalCount); } } else { // didn't get content-type header $this->output('Msg #' . $x . ' is not a well-formatted MIME mail, missing Content-Type', self::VERBOSE_REPORT); if ($this->debugBodyRule) { $this->output(' Headers: ' . $this->bmhNewLine . $header . $this->bmhNewLine, self::VERBOSE_DEBUG); } $processed = $this->processBounce($x, 'BODY', $totalCount); } } $deleteFlag[$x] = false; $moveFlag[$x] = false; if ($processed) { $processedCount++; if (!$this->disableDelete) { // delete the bounce if not in disableDelete mode if (!$this->testMode) { @imap_delete($this->mailboxLink, $x); } $deleteFlag[$x] = true; $deletedCount++; } elseif ($this->moveHard) { // check if the move directory exists, if not create it if (!$this->testMode) { $this->mailboxExist($this->hardMailbox); } // move the message if (!$this->testMode) { @imap_mail_move($this->mailboxLink, $x, $this->hardMailbox); } $moveFlag[$x] = true; $movedCount++; } elseif ($this->moveSoft) { // check if the move directory exists, if not create it if (!$this->testMode) { $this->mailboxExist($this->softMailbox); } // move the message if (!$this->testMode) { @imap_mail_move($this->mailboxLink, $x, $this->softMailbox); } $moveFlag[$x] = true; $movedCount++; } } else { // not processed $unprocessedCount++; if (!$this->disableDelete && $this->purgeUnprocessed) { // delete this bounce if not in disableDelete mode, and the flag BOUNCE_PURGE_UNPROCESSED is set if (!$this->testMode) { @imap_delete($this->mailboxLink, $x); } $deleteFlag[$x] = true; $deletedCount++; } } flush(); } $this->output($this->bmhNewLine . 'Closing mailbox, and purging messages'); imap_close($this->mailboxLink); $this->output('Read: ' . $fetchedCount . ' messages'); $this->output($processedCount . ' action taken'); $this->output($unprocessedCount . ' no action taken'); $this->output($deletedCount . ' messages deleted'); $this->output($movedCount . ' messages moved'); return true; }
/** * 移动/移除 邮件 * @param $mid */ public function removeEamil($mid) { if (!$this->marubox) { return false; } else { imap_mail_move($this->marubox, $mid, 'INBOX'); } }
function archiveEmail($id) { global $CONFIG; if ($CONFIG['debug']) { debug_log("Moving mail to {$CONFIG['email_archive_folder']} folder"); } return imap_mail_move($this->mailbox, $id, $CONFIG['email_archive_folder']) or debug_log(imap_last_error()); }
/** * Move message to another mailbox * * @param Mailbox $mailbox * * @throws MessageMoveException * @return Message */ public function move(Mailbox $mailbox) { if (!imap_mail_move($this->stream, $this->messageNumber, $mailbox->getName(), \CP_UID)) { throw new MessageMoveException($this->messageNumber, $mailbox->getName()); } return $this; }
/** * Moves a msg to a different folder * * @param <int> $msgId id number of the msg in current mailbox * @param <string> $new_folder new folder's name * @param <bool> $create create folder if doesn't exist ? * @return <bool> true/false according to success */ public function moveMsg($msgId, $new_folder, $create = true) { if (!$this->connectIfNeeded()) { return false; } if ($create) { @imap_createmailbox($this->connection, imap_utf7_encode('{' . $this->hostname . '}' . $new_folder)); } $success = @imap_mail_move($this->connection, $msgId, $new_folder, CP_UID); @imap_expunge($this->connection); return $success; }
/** * Function which moves mail to another folder * @param String $msgno - List of message number separated by commas * @param String $folderName - folder name */ public function moveMail($msgno, $folderName) { // SalesPlatform begin $msgno = urldecode($msgno); // SalesPlatform end $msgno = trim($msgno, ','); $msgno = explode(',', $msgno); $folder = $this->convertCharacterEncoding(html_entity_decode($folderName), 'UTF7-IMAP', 'UTF-8'); //handle both utf8 characters and html entities for ($i = 0; $i < count($msgno); $i++) { @imap_mail_move($this->mBox, $msgno[$i], $folder); } @imap_expunge($this->mBox); }
function MoveMessage($folderid, $id, $newfolderid) { debugLog("IMAP-MoveMessage: (sfid: '{$folderid}' id: '{$id}' dfid: '{$newfolderid}' )"); $this->imap_reopenFolder($folderid); // read message flags $overview = @imap_fetch_overview($this->_mbox, $id, FT_UID); if (!$overview) { debugLog("IMAP-MoveMessage: Failed to retrieve overview"); return false; } else { // move message $s1 = imap_mail_move($this->_mbox, $id, str_replace(".", $this->_serverdelimiter, $newfolderid), FT_UID); // delete message in from-folder $s2 = imap_expunge($this->_mbox); // open new folder $this->imap_reopenFolder($newfolderid); // remove all flags $s3 = @imap_clearflag_full($this->_mbox, $id, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID); $newflags = ""; if ($overview[0]->seen) { $newflags .= "\\Seen"; } if ($overview[0]->flagged) { $newflags .= " \\Flagged"; } if ($overview[0]->answered) { $newflags .= " \\Answered"; } $s4 = @imap_setflag_full($this->_mbox, $id, $newflags, FT_UID); debugLog("MoveMessage: (" . $folderid . "->" . $newfolderid . ") s-move: {$s1} s-expunge: {$s2} unset-Flags: {$s3} set-Flags: {$s4}"); return $s1 && $s2 && $s3 && $s4; } }
/** * Called when the user moves an item on the PDA from one folder to another * * @param string $folderid id of the source folder * @param string $id id of the message * @param string $newfolderid id of the destination folder * * @access public * @return boolean status of the operation * @throws StatusException could throw specific SYNC_MOVEITEMSSTATUS_* exceptions */ public function MoveMessage($folderid, $id, $newfolderid) { ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s')", $folderid, $id, $newfolderid)); $folderImapid = $this->getImapIdFromFolderId($folderid); $newfolderImapid = $this->getImapIdFromFolderId($newfolderid); $this->imap_reopenFolder($folderImapid); // TODO this should throw a StatusExceptions on errors like SYNC_MOVEITEMSSTATUS_SAMESOURCEANDDEST,SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID,SYNC_MOVEITEMSSTATUS_CANNOTMOVE // read message flags $overview = @imap_fetch_overview($this->mbox, $id, FT_UID); if (!$overview) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to retrieve overview of source message: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID); } else { // get next UID for destination folder // when moving a message we have to announce through ActiveSync the new messageID in the // destination folder. This is a "guessing" mechanism as IMAP does not inform that value. // when lots of simultaneous operations happen in the destination folder this could fail. // in the worst case the moved message is displayed twice on the mobile. $destStatus = imap_status($this->mbox, $this->server . $newfolderImapid, SA_ALL); if (!$destStatus) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to open destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDDESTID); } $newid = $destStatus->uidnext; // move message $s1 = imap_mail_move($this->mbox, $id, $newfolderImapid, CP_UID); if (!$s1) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, copy to destination folder failed: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // delete message in from-folder $s2 = imap_expunge($this->mbox); // open new folder $stat = $this->imap_reopenFolder($newfolderImapid); if (!$s1) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, openeing the destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // remove all flags $s3 = @imap_clearflag_full($this->mbox, $newid, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID); $newflags = ""; if ($overview[0]->seen) { $newflags .= "\\Seen"; } if ($overview[0]->flagged) { $newflags .= " \\Flagged"; } if ($overview[0]->answered) { $newflags .= " \\Answered"; } $s4 = @imap_setflag_full($this->mbox, $newid, $newflags, FT_UID); ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): result s-move: '%s' s-expunge: '%s' unset-Flags: '%s' set-Flags: '%s'", $folderid, $id, $newfolderid, Utils::PrintAsString($s1), Utils::PrintAsString($s2), Utils::PrintAsString($s3), Utils::PrintAsString($s4))); // return the new id "as string"" return $newid . ""; } }
function mailcwp_delete_callback() { $result = array(); $mailcwp_session = mailcwp_get_session(); if (!isset($mailcwp_session) || empty($mailcwp_session)) { return; } $account = $mailcwp_session["account"]; $use_ssl = $account["use_ssl"]; //$from = $account["email"]; $folder = $mailcwp_session["folder"]; $use_tls = $account["use_tls"]; $messages = $_POST["messages"]; //write_log($messages); //write_log("DELETE MAIL " . print_r($account, true)); $use_ssl_flag = $use_ssl === "true" ? "/ssl" : ""; $use_tls_flag = $use_tls === "true" ? "/tls" : ""; $mbox = mailcwp_imap_connect($account, 0, $folder); //write_log("SEND ACCOUNT " . print_r($account)); $sent_folder = ""; if (is_array($account)) { $trash_folder = $account["trash_folder"]; if (empty($trash_folder)) { $trash_folder = mailcwp_find_folder($mbox, $account, "Trash"); if (empty($trash_folder)) { $trash_folder = mailcwp_find_folder($mbox, $account, "Deleted"); } } if (!empty($trash_folder) && $trash_folder != $folder) { //write_log("DELETE MOVE MESSAGES " . print_r($messages, true)); imap_mail_move($mbox, $messages, $trash_folder); imap_expunge($mbox); $result["result"] = "OK"; $result["message"] = "Moved to {$trash_folder}"; $result["imap_errors"] = imap_errors(); } else { imap_setflag_full($mbox, $messages, "\\Deleted"); $result["result"] = "OK"; if (!empty($trash_folder) && $folder == $trash_folder) { imap_expunge($mbox); $result["message"] = "Permanently Deleted"; } else { $result["message"] = "Marked as Deleted"; } $result["imap_errors"] = imap_errors(); } } else { $result["result"] = "Failed"; $result["message"] = "Account not found."; } //write_log("DELETE MESSAGES ($messages) " . print_r(imap_errors(), true)); echo json_encode($result); die; }
/** * Called when the user moves an item on the PDA from one folder to another * * @param string $folderid id of the source folder * @param string $id id of the message * @param string $newfolderid id of the destination folder * @param ContentParameters $contentparameters * * @access public * @return boolean status of the operation * @throws StatusException could throw specific SYNC_MOVEITEMSSTATUS_* exceptions */ public function MoveMessage($folderid, $id, $newfolderid, $contentparameters) { ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s')", $folderid, $id, $newfolderid)); $folderImapid = $this->getImapIdFromFolderId($folderid); // SDB: When iOS is configured to "Archive Message" (instead of Delete Message), it will send a "MoveItems" // command to the Exchange server and attempt to move it to a folder called "0/Archive". Instead, we trap that // and send it to "[Gmail]/All Mail" folder instead. Note, that when on iOS device and you trigger a move from // folder A to B, it will correctly move that email, including to all folders with "[Gmail]...". if ($newfolderid == "0/Archive") { $newfolderImapid = "[Gmail]/All Mail"; } else { $newfolderImapid = $this->getImapIdFromFolderId($newfolderid); } if ($folderImapid == $newfolderImapid) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, destination folder is source folder. Canceling the move.", $folderid, $id, $newfolderid), SYNC_MOVEITEMSSTATUS_SAMESOURCEANDDEST); } $this->imap_reopen_folder($folderImapid); if ($this->imap_inside_cutoffdate(Utils::GetCutOffDate($contentparameters->GetFilterType()), $id)) { // read message flags $overview = @imap_fetch_overview($this->mbox, $id, FT_UID); if (!is_array($overview)) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to retrieve overview of source message: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID); } else { // get next UID for destination folder // when moving a message we have to announce through ActiveSync the new messageID in the // destination folder. This is a "guessing" mechanism as IMAP does not inform that value. // when lots of simultaneous operations happen in the destination folder this could fail. // in the worst case the moved message is displayed twice on the mobile. $destStatus = imap_status($this->mbox, $this->server . $newfolderImapid, SA_ALL); if (!$destStatus) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to open destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDDESTID); } $newid = $destStatus->uidnext; // move message $s1 = imap_mail_move($this->mbox, $id, $newfolderImapid, CP_UID); if (!$s1) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, copy to destination folder failed: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // delete message in from-folder $s2 = imap_expunge($this->mbox); // open new folder $stat = $this->imap_reopen_folder($newfolderImapid); if (!$s1) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, opening the destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // remove all flags $s3 = @imap_clearflag_full($this->mbox, $newid, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID); $newflags = ""; if ($overview[0]->seen) { $newflags .= "\\Seen"; } if ($overview[0]->flagged) { $newflags .= " \\Flagged"; } if ($overview[0]->answered) { $newflags .= " \\Answered"; } $s4 = @imap_setflag_full($this->mbox, $newid, $newflags, FT_UID); ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): result s-move: '%s' s-expunge: '%s' unset-Flags: '%s' set-Flags: '%s'", $folderid, $id, $newfolderid, Utils::PrintAsString($s1), Utils::PrintAsString($s2), Utils::PrintAsString($s3), Utils::PrintAsString($s4))); // return the new id "as string" return $newid . ""; } } else { throw new StatusException(sprintf("BackendIMAP->MoveMessage(): Message is outside the sync range"), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID); } }
/** * postbyemail_imap() * * Grabs unread messages from an imap account and saves them as .eml files * Passes any new messages found to the postby email function for processing * Called by a scheduled task or cronjob */ function postbyemail_imap() { global $modSettings; // No imap, why bother? if (!function_exists('imap_open')) { return false; } // Values used for the connection $hostname = !empty($modSettings['maillist_imap_host']) ? $modSettings['maillist_imap_host'] : ''; $username = !empty($modSettings['maillist_imap_uid']) ? $modSettings['maillist_imap_uid'] : ''; $password = !empty($modSettings['maillist_imap_pass']) ? $modSettings['maillist_imap_pass'] : ''; $mailbox = !empty($modSettings['maillist_imap_mailbox']) ? $modSettings['maillist_imap_mailbox'] : 'INBOX'; $type = !empty($modSettings['maillist_imap_connection']) ? $modSettings['maillist_imap_connection'] : ''; // I suppose that without these informations we can't do anything. if (empty($hostname) || empty($username) || empty($password)) { return; } // Based on the type selected get/set the additional connection details $connection = port_type($type); $hostname .= strpos($hostname, ':') === false ? ':' . $connection['port'] : ''; $server = '{' . $hostname . '/' . $connection['protocol'] . $connection['flags'] . '}'; $mailbox = $server . imap_utf7_encode($mailbox); // Connect to the mailbox using the supplied credentials and protocol $inbox = @imap_open($mailbox, $username, $password); if ($inbox === false) { return false; } // If using gmail, we may need the trash bin name as well $trash_bin = ''; if (!empty($modSettings['maillist_imap_delete']) && strpos($hostname, '.gmail.') !== false) { $trash_bin = get_trash_folder($inbox, $server); } // Grab all unseen emails, return by message ID $emails = imap_search($inbox, 'UNSEEN', SE_UID); // You've got mail, if ($emails) { // Initialize Emailpost controller require_once CONTROLLERDIR . '/Emailpost.controller.php'; $controller = new Emailpost_Controller(); // Make sure we work from the oldest to the newest message sort($emails); // For every email... foreach ($emails as $email_uid) { // Get the headers and prefetch the body as well to avoid a second request $headers = imap_fetchheader($inbox, $email_uid, FT_PREFETCHTEXT | FT_UID); $message = imap_body($inbox, $email_uid, FT_UID); // Create the save-as email if (!empty($headers) && !empty($message)) { $email = $headers . "\n" . $message; $controller->action_pbe_post($email); // Mark it for deletion? if (!empty($modSettings['maillist_imap_delete'])) { // Gmail labels make this more complicated if (strpos($hostname, '.gmail.') !== false) { imap_mail_move($inbox, $email_uid, $trash_bin, CP_UID); } imap_delete($inbox, $email_uid, FT_UID); imap_expunge($inbox); } } } // Close the connection imap_close($inbox); return true; } else { return false; } }
if ($overview[0]->from == "*****@*****.**" && $overview[0]->seen == 0) { // if ( $overview[0]->from == "*****@*****.**" ) { // $output.= "". $email_number ." - "; // $output.= "". $overview[0]->from .": "; // $output.= "". $overview[0]->subject.": "; // $output.= "". $overview[0]->seen ."\n"; // $output.= "". $overview[0]->date ."\n"; $message = imap_fetchbody($inbox, $email_number, 1); // echo $output; // echo $message; date_default_timezone_set("America/New_York"); $date = date_create($overview[0]->date); $filename = date_format($date, 'dMY'); // $path = "$myhome/temp/Grades/"; // $f = fopen("$myhome/file.txt", "w"); $f = fopen($path . "" . $filename . "", "w"); fwrite($f, "" . $message . ""); fclose($f); // 10Dec2013 imap_mail_move($inbox, "{$email_number}", 'School'); break; } } } /* close the connection */ imap_close($inbox); } //else { // echo "$filename IS in $path\n"; // exit(0); //}
/** * move the message to another mailbox * wraps imap_mail_move() function * This is only applicable to IMAP connections */ public function move_mail($id_or_range, $mailbox_name) { $bool = imap_mail_move($this->resource, $id_or_range, $mailbox_name); $this->log_state('Moved message: ' . $id_or_range . ' to mailbox ' . $mailbox_name); }
/** * @name: getmails * holt x Mails aus dem Postfach und parst diese nach Parts, oder sucht nur nach $subject * * @param $subject * @return Boolean */ public function getmails($subject = 0) { imap_expunge($this->connection); $check = imap_mailboxmsginfo($this->connection); if (isset($subject) && !empty($subject)) { $mails = imap_search($this->connection, 'UNSEEN SUBJECT "' . substr(urldecode(subject), 0, 45) . '"', SE_UID); } else { $mails[0] = '*'; } $mails = imap_fetch_overview($this->connection, "1:" . $mails[0], FT_UID); // Holt eine Uebersicht aller Emails $size = count($mails); // Anzahl der Nachrichten if ($size >= $this->config['counter']) { $size = $this->config['counter']; } for ($i = 0; $i < $size; $i++) { if ($i >= $this->config['counter']) { break; } $mails[$i]->subject = imap_utf8($mails[$i]->subject); $header = imap_fetchheader($this->connection, $mails[$i]->msgno); $struct = imap_fetchstructure($this->connection, $mails[$i]->msgno); $report = imap_fetchbody($this->connection, $mails[$i]->msgno, 2); $body = imap_fetchbody($this->connection, $mails[$i]->msgno, 1); $logs = imap_fetchbody($this->connection, $mails[$i]->msgno, 3); $this->mail[$i] = array('header' => $header, 'body' => $body, 'report' => $report, 'logs' => $logs, 'structur' => $struct, 'all' => $mails[$i]); $this->msgnr = $mails[$i]->msgno; if ($this->config['afterparse'] == 'delete') { imap_delete($this->connection, $mails[$i]->msgno . ':*'); } elseif ($this->config['afterparse'] == 'move') { imap_mail_move($this->connection, $mails[$i]->msgno, $config['ordner'] . '.' . $this->config['movebox']); } } if ($this->config['afterparse'] == 'delete_all') { imap_delete($this->connection, "*"); } imap_expunge($this->connection); if (!is_array($mails)) { $this->mail = 0; } return $this->mail; }
/** * Called when the user moves an item on the PDA from one folder to another * * @param string $folderid id of the source folder * @param string $id id of the message * @param string $newfolderid id of the destination folder * @param ContentParameters $contentparameters * * @access public * @return boolean status of the operation * @throws StatusException could throw specific SYNC_MOVEITEMSSTATUS_* exceptions */ public function MoveMessage($folderid, $id, $newfolderid, $contentparameters) { ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s')", $folderid, $id, $newfolderid)); $folderImapid = $this->getImapIdFromFolderId($folderid); $newfolderImapid = $this->getImapIdFromFolderId($newfolderid); if ($folderImapid == $newfolderImapid) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, destination folder is source folder. Canceling the move.", $folderid, $id, $newfolderid), SYNC_MOVEITEMSSTATUS_SAMESOURCEANDDEST); } $this->imap_reopen_folder($folderImapid); if ($this->imap_inside_cutoffdate(Utils::GetCutOffDate($contentparameters->GetFilterType()), $id)) { // read message flags $overview = @imap_fetch_overview($this->mbox, $id, FT_UID); if (!is_array($overview)) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to retrieve overview of source message: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID); } else { // get next UID for destination folder // when moving a message we have to announce through ActiveSync the new messageID in the // destination folder. This is a "guessing" mechanism as IMAP does not inform that value. // when lots of simultaneous operations happen in the destination folder this could fail. // in the worst case the moved message is displayed twice on the mobile. $destStatus = imap_status($this->mbox, $this->server . $newfolderImapid, SA_ALL); if (!$destStatus) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to open destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDDESTID); } $newid = $destStatus->uidnext; // move message $s1 = imap_mail_move($this->mbox, $id, $newfolderImapid, CP_UID); if (!$s1) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, copy to destination folder failed: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // delete message in from-folder $s2 = imap_expunge($this->mbox); // open new folder $stat = $this->imap_reopen_folder($newfolderImapid); if (!$stat) { throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, opening the destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE); } // remove all flags $s3 = @imap_clearflag_full($this->mbox, $newid, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID); $newflags = ""; $move_to_trash = strcasecmp($newfolderImapid, $this->create_name_folder(IMAP_FOLDER_TRASH)) == 0; if ($overview[0]->seen || $move_to_trash && defined('IMAP_AUTOSEEN_ON_DELETE') && IMAP_AUTOSEEN_ON_DELETE == true) { $newflags .= "\\Seen"; } if ($overview[0]->flagged) { $newflags .= " \\Flagged"; } if ($overview[0]->answered) { $newflags .= " \\Answered"; } $s4 = @imap_setflag_full($this->mbox, $newid, $newflags, FT_UID); ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): result s-move: '%s' s-expunge: '%s' unset-Flags: '%s' set-Flags: '%s'", $folderid, $id, $newfolderid, Utils::PrintAsString($s1), Utils::PrintAsString($s2), Utils::PrintAsString($s3), Utils::PrintAsString($s4))); // return the new id "as string" return $newid . ""; } } else { throw new StatusException(sprintf("BackendIMAP->MoveMessage(): Message is outside the sync range"), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID); } }
/** * moves emails from folder to folder * @param string $fromIe I-E id * @param string $fromFolder IMAP path to folder in which the email lives * @param string $toIe I-E id * @param string $toFolder * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP * UIDs * @param bool $copy Default false * @return bool True on successful execution */ function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy = false) { global $app_strings; global $current_user; // same I-E server if ($fromIe == $toIe) { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E"); //$exDestFolder = explode("::", $toFolder); //preserve $this->mailbox if (isset($this->mailbox)) { $oldMailbox = $this->mailbox; } $this->retrieve($fromIe); $this->mailbox = $fromFolder; $this->connectMailserver(); $exUids = explode('::;::', $uids); $uids = implode(",", $exUids); // imap_mail_move accepts comma-delimited lists of UIDs if ($copy) { if (imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) { $this->mailbox = $toFolder; $this->connectMailserver(); $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID); $this->updateOverviewCacheFile($newOverviews, 'append'); if (isset($oldMailbox)) { $this->mailbox = $oldMailbox; } return true; } else { $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); } } else { if (imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) { $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); imap_expunge($this->conn); // hard deletes moved messages // update cache on fromFolder $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true); $this->deleteCachedMessages($uids, $fromFolder); // update cache on toFolder $this->checkEmailOneMailbox($toFolder, true, true); if (isset($oldMailbox)) { $this->mailbox = $oldMailbox; } return true; } else { $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); } } } elseif ($toIe == 'folder' && $fromFolder == 'sugar::Emails') { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder"); // move from sugar folder to sugar folder require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids); foreach ($exUids as $id) { if ($copy) { $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails"); } else { $fromSugarFolder = new SugarFolder(); $fromSugarFolder->retrieve($fromIe); $toSugarFolder = new SugarFolder(); $toSugarFolder->retrieve($toFolder); $email = new Email(); $email->retrieve($id); $email->status = 'unread'; // when you move from My Emails to Group Folder, Assign To field for the Email should become null if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) { $email->assigned_user_id = ""; $email->save(); if (!$toSugarFolder->checkEmailExistForFolder($id)) { $fromSugarFolder->deleteEmailFromAllFolder($id); $toSugarFolder->addBean($email); } } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) { $fromSugarFolder->deleteEmailFromAllFolder($id); $email->assigned_user_id = $current_user->id; $email->save(); } else { // If you are moving something from personal folder then delete an entry from all folder if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) { $fromSugarFolder->deleteEmailFromAllFolder($id); } // if if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) { $email->assigned_user_id = ""; $toSugarFolder->addBean($email); } // if if (!$toSugarFolder->checkEmailExistForFolder($id)) { if (!$toSugarFolder->is_dynamic) { $fromSugarFolder->deleteEmailFromAllFolder($id); $toSugarFolder->addBean($email); } else { $fromSugarFolder->deleteEmailFromAllFolder($id); $email->assigned_user_id = $current_user->id; } } else { $sugarFolder->move($fromIe, $toFolder, $id); } // else $email->save(); } // else } } return true; } elseif ($toIe == 'folder') { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder"); // move to Sugar folder require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $sugarFolder->retrieve($toFolder); //Show the import form if we don't have the required info if (!isset($_REQUEST['delete'])) { $json = getJSONobj(); if ($sugarFolder->is_group) { $_REQUEST['showTeam'] = false; $_REQUEST['showAssignTo'] = false; } $ret = $this->email->et->getImportForm($_REQUEST, $this->email); $ret['move'] = true; $ret['srcFolder'] = $fromFolder; $ret['srcIeId'] = $fromIe; $ret['dstFolder'] = $toFolder; $ret['dstIeId'] = $toIe; $out = trim($json->encode($ret, false)); echo $out; return true; } // import to Sugar $this->retrieve($fromIe); $this->mailbox = $fromFolder; $this->connectMailserver(); // If its a group folder the team should be of the folder team if ($sugarFolder->is_group) { $_REQUEST['team_id'] = $sugarFolder->team_id; $_REQUEST['team_set_id'] = $sugarFolder->team_set_id; } else { // TODO - set team_id, team_set for new UI } // else $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids); if (!empty($sugarFolder->id)) { $count = 1; $return = array(); $json = getJSONobj(); foreach ($exUids as $k => $uid) { $msgNo = $uid; if ($this->isPop3Protocol()) { $msgNo = $this->getCorrectMessageNoForPop3($uid); } else { $msgNo = imap_msgno($this->conn, $uid); } if (!empty($msgNo)) { $importStatus = $this->importOneEmail($msgNo, $uid); // add to folder if ($importStatus) { $sugarFolder->addBean($this->email); if (!$copy && isset($_REQUEST['delete']) && $_REQUEST['delete'] == "true" && $importStatus) { $GLOBALS['log']->error("********* delete from mailserver [ {explode(", ", {$uids})} ]"); // delete from mailserver $this->deleteMessageOnMailServer($uid); $this->deleteMessageFromCache($uid); } // if } $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($importStatus ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']); $count++; } // if } // foreach echo $json->encode($return); return true; } else { $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]"); } } else { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria"); } return false; }
/** * Move message to another mailbox * * @param integer $msgno Message number to move * @param string $mbox Mailbox to move message to * @return boolean */ function move($msgno, $mbox) { // Only imap supports moving of mesages if ($server_type == "imap") { $list = imap_list($this->conn, $this->server, "*"); if (!in_array($mbox, $list)) { if (!imap_createmailbox($this->conn, imap_utf7_encode($this->server . $mbox))) { // $_ENV['api']['sys']->log("Creation of $mbox mailbox failed!","mailer"); } } return imap_mail_move($this->conn, $msgno, $mbox); } else { return imap_delete($this->conn, $msgno); } }
/** * Function which moves mail to another folder * @param String $msgno - List of message number separated by commas * @param String $folderName - folder name */ function moveMail($msgno, $folderName) { $msgno = trim($msgno, ','); $msgno = explode(',', $msgno); for ($i = 0; $i < count($msgno); $i++) { @imap_mail_move($this->mBox, $msgno[$i], $folderName); } @imap_expunge($this->mBox); }
/** * Moves mails listed in mailId into new mailbox * @return bool */ public function moveMail($mailId, $mailBox) { return imap_mail_move($this->getImapStream(), $mailId, $mailBox, CP_UID) && $this->expungeDeletedMails(); }
} } } if ($email !== false) { //echo 'Activate for "'.$headers['x-twittersenderscreenname'].'"'."\n"; if (!User::Activate($headers['x-twittersenderscreenname'], $email)) { echo ' Failed to activate user "' . $headers['x-twittersenderscreenname'] . '": ' . mysql_error(GetDB()) . "\n"; } } break; default: echo 'Unknown type: "' . $headers['x-twitteremailtype'] . '"' . "\n"; var_dump($headers); break; } // Move to [Google Mail]/All Mail after processing @imap_mail_move($mbox, $msgid, '[Google Mail]/All Mail'); } } } @imap_close($mbox); $content = trim(ob_get_clean()); if (strlen($content) > 0) { @mail('*****@*****.**', 'TwitApps Replies Errors', $content); } // Didn't process anything, rest for a while if ($processed == 0) { //echo "Sleeping...\n"; sleep(60); } }
function fetchEmails() { if (!$this->connect()) { return false; } $archiveFolder = $this->getArchiveFolder(); $delete = $this->canDeleteEmails(); $max = $this->getMaxFetch(); $nummsgs = imap_num_msg($this->mbox); //echo "New Emails: $nummsgs\n"; $msgs = $errors = 0; for ($i = $nummsgs; $i > 0; $i--) { //process messages in reverse. if ($this->createTicket($i)) { imap_setflag_full($this->mbox, imap_uid($this->mbox, $i), "\\Seen", ST_UID); //IMAP only?? if ((!$archiveFolder || !imap_mail_move($this->mbox, $i, $archiveFolder)) && $delete) { imap_delete($this->mbox, $i); } $msgs++; $errors = 0; //We are only interested in consecutive errors. } else { $errors++; } if ($max && ($msgs >= $max || $errors > $max * 0.8)) { break; } } //Warn on excessive errors if ($errors > $msgs) { $warn = sprintf(_S('Excessive errors processing emails for %1$s/%2$s. Please manually check the inbox.'), $this->getHost(), $this->getUsername()); $this->log($warn); } @imap_expunge($this->mbox); return $msgs; }
/** * Delete mail from that mail box * * @param $mid String mail Id * @param $folder String folder to move (delete if empty) (default '') * * @return Boolean **/ function deleteMails($mid, $folder = '') { if (!empty($folder) && isset($this->fields[$folder]) && !empty($this->fields[$folder])) { $name = mb_convert_encoding($this->fields[$folder], "UTF7-IMAP", "UTF-8"); if (imap_mail_move($this->marubox, $mid, $name)) { return true; } // raise an error and fallback to delete //TRANS: %1$s is the name of the folder, %2$s is the name of the receiver trigger_error(sprintf(__('Invalid configuration for %1$s folder in receiver %2$s'), $folder, $this->getName())); } return imap_delete($this->marubox, $mid); }
$elist = $MailBox->mailList; $num_mails = $elist['count']; $start_page = cal_start($num_mails, $MailBox->mails_per_page); imap_close($MailBox->mbox); echo "start=" . $start_page . ";"; echo "ids='" . $mailid . "';"; flush(); exit; } if ($_POST["command"] == "move_msg" && $_POST["ajax"] == "true") { $MailBox = new MailBox($mailbox); if (isset($_REQUEST["mailid"]) && $_REQUEST["mailid"] != '') { $mailids = explode(':', $_REQUEST["mailid"]); } foreach ($mailids as $mailid) { imap_mail_move($MailBox->mbox, $mailid, $_REQUEST["mvbox"]); } imap_expunge($MailBox->mbox); imap_close($MailBox->mbox); $MailBox = new MailBox($mailbox); $elist = $MailBox->mailList; $num_mails = $elist['count']; $start_page = cal_start($num_mails, $MailBox->mails_per_page); imap_close($MailBox->mbox); echo $start_page; flush(); exit; } if ($command == "undelete_msg") { $MailBox = new MailBox($mailbox); $email = new Webmails($MailBox->mbox, $mailid);
public function fetch(MailCriteria $criteria, $callback) { $mailbox = @imap_open('{' . $this->host . ':' . $this->port . '}INBOX', $this->username, $this->password); if (!$mailbox) { throw new ImapException("Cannot connect to imap server: {$this->host}:{$this->port}'"); } $this->checkProcessedFolder($mailbox); $emails = $this->fetchEmails($mailbox, $criteria); if ($emails) { foreach ($emails as $emailIndex) { $overview = imap_fetch_overview($mailbox, $emailIndex, 0); $message = imap_body($mailbox, $emailIndex); $email = new Email($overview, $message); $processed = $callback($email); if ($processed) { $res = imap_mail_move($mailbox, $emailIndex, $this->processedFolder); if (!$res) { throw new \Exception("Unexpected error: Cannot move email to "); break; } } } } @imap_close($mailbox); }
for ($X = 1; $X <= $msgCount; $X++) { // loop over the messages $info = imap_fetchstructure($mbox, $X); //$X is the message number //echo "<br> data from email -> ";print"<pre>";print_r($info);print"</pre>"; $numparts = count($info->parts); // how may parts the message has $Y = 2; //setting up a counter..not elegant, but it will work foreach ($info->parts as $part) { //loop over the parts of the message part 1 is message body ( doesn't contain 'disposition') part 2 is the attachment if (isset($part->disposition)) { if ($part->disposition == 'attachment') { $name = $part->dparameters[1]->value; //echo 'the attachment -> ' . $name. '<br>' ; //write the file to the folder $file = imap_fetchbody($mbox, $X, $Y); $dec = base64_decode($file); file_put_contents($path . $name, $dec); //move the emails to the completed mailbox //echo 'the path -> ' . $path.$name; imap_mail_move($mbox, $X, 'Inbox/Completed'); $Y = $Y + 1; //incase there are more than 1 attachments } } } } //leave the moving of emails to the cron version imap_expunge($mbox); imap_close($mbox);