imap_delete not working - php

I am using php imap functions to parse the message from webmail. I can fetch messages one by one and save them in DB. After saving, I want to delete the inbox message. imap_delete function is not working here. My code is like that:
$connection = pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false);//connect
$stat = pop3_list($connection);//list messages
foreach($stat as $line) {
//save in db codes...
imap_delete($connection, $line['msgno']);//flag as delete
}
imap_close($connection, CL_EXPUNGE);
I also tested - imap_expunge($connection);
But it is not working. The messages are not deleted. Please help me out...

You are mixing POP and IMAP.
That is not going to work. You need to open the connection with IMAP. See this example:
<?php
$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
or die("Can't connect: " . imap_last_error());
$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";
imap_delete($mbox, 1);
$check = imap_mailboxmsginfo($mbox);
echo "Messages after delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($mbox);
$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
imap_close($mbox);
?>

Actually the functions names are like pop3. but they perform imap functionality. like -
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
$ssl=($ssl==false)?"/novalidate-cert":"";
return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_list($connection,$message="")
{
if ($message)
{
$range=$message;
} else {
$MC = imap_check($connection);
$range = "1:".$MC->Nmsgs;
}
$response = imap_fetch_overview($connection,$range);
foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
return $result;
}

Related

PHP - Login via form and grab cookie

I'm trying to login to the following URL: pitangui.amazon.com
I have tried using cURL as well as libraries like https://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
However, I'm getting the following error using the webscraper via Amazon:
This is my PHP code:
<?php
require_once "support/http.php";
require_once "support/web_browser.php";
require_once "support/simple_html_dom.php";
$url = "https://pitangui.amazon.com";
$web = new WebBrowser(array("extractforms" => true));
$result = $web->Process($url);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
$form = $result["forms"][0];
$form->SetFormValue("email", "myemail#gmail.com");
$form->SetFormValue("password", "mypass");
$result2 = $form->GenerateFormRequest("signIn");
$result = $web->Process($result2["url"], "auto", $result2["options"]);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
// Do something with the results page here...
print_r($result);
}
}
?>
I'm first trying to get the login working, then I will grab the cookie via $_SERVER['Cookie']
add
$form->SetFormValue("create","0");

How to create a page periodically using wiki bot

My prime aim is to get a page , parse the text and create a subpage periodically depending on the text. To get a page ,create and login, i have the following code .Php version-5.3.3,server:localhost
private function login($username, $password, $wiki) {
$response = $this->postAPI($wiki, 'api.php?', 'action=login&lgname=' . urlencode($username) . '&lgpassword=' . urlencode($password));
if ($response['login']['result'] == "Success") {
//Unpatched server, all done
} elseif ($response['login']['result'] == "NeedToken") {
//Patched server, going fine
$token = $response['login']['token'];
$newresponse = $this->postAPI($wiki, 'api.php?', 'action=login&lgname=' . urlencode($username) . '&lgpassword=' . urlencode($password) . '&lgtoken=' . $token);
if ($newresponse['login']['result'] == "Success") {
//All done
} else {
echo "Forced by server to wait. Automatically trying again.<br />\n";
sleep(10);
$this->login($username, $password, $wiki);
}
} else {
//Problem
if (isset($response['login']['wait']) || (isset($response['error']['code']) && $response['error']['code'] == "maxlag")) {
echo "Forced by server to wait. Automatically trying again.<br />\n";
sleep(10);
$this->login($username, $password, $wiki);
} else {
die("Login failed: " . $response . "\r<br />\n");
}
}
}
Function to get a page is:
public function get_page($page, $wiki = "")//get page's content
{
$response = $this->callAPI($wiki, 'api.php?action=query&prop=revisions&titles=' . urlencode($page) . '&rvprop=content');
if (is_array($response)) {
$array = $response['query']['pages'];
$array = array_shift($array);
$pageid = $array["pageid"];
return $response['query']['pages'][$pageid]['revisions'][0]["*"];
} else {
echo "Unknown get_page error.<br />\n";
return false;
}
}
I have a problem with login. I always get Forced by server to wait. Automatically trying again regardless my password and id is correct. Infact the URI works properly if given manually.And if i try to create a page or get a category, i get the following error:
Cannot modify header information - headers already sent by (output started at serverlocation/Phpwikibot.php:188) in serverlocation/includes/WebResponse.php
Can some one help me with this issue?
You say "localhost", so you have server-side access and you should be using the internal PHP API, not the web API. In particular, to edit a page you can use maintenance/edit.php. See a real world example I used for some Wikimedia wikis:
#!/bin/bash
{
# Stuff
# Fetch stuff
echo -e $stuff
} | php edit.php --user "FuzzyBot" \
--bot --summary "Update stats" "Meta:Babylon/Translation_stats"

Is there an alternative to php imap extension

My godaddy shared hosing service will not enable the IMAP extension for PHP. So I am in a pickle:
Is there a PHP function to replace the IMAP feature in PHP ?
Here is the error:
Fatal error: Call to undefined function imap_last_error()
Here is the sample code that I am having problems with:
$mbox = imap_open ('{'.$email_host.':'.$email_port.'/pop3/novalidate-cert}INBOX', $email_username, $email_password) or die(imap_last_error());
if(!$mbox){
// send email letting them know bounce checking failed?
// meh. later.
echo 'Failed to connect when checking bounces.';
}else{
$MC = imap_check($mbox);
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
$this_subject = (string)$overview->subject;
//echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from} <br> {$this_subject} <br>\n";
$tmp_file = tempnam('/tmp/','newsletter_bounce');
// TODO - tmp files for windows hosting.
imap_savebody ($mbox, $tmp_file, $overview->msgno);
$body = file_get_contents($tmp_file);
if(preg_match('/Message-ID:\s*<?Newsletter-(\d+)-(\d+)-([A-Fa-f0-9]{32})/imsU',$body,$matches)){
// we have a newsletter message id, check the hash and mark a bounce.
//"message_id" => "Newsletter-$send_id-$member_id-".md5("bounce check for $member_id in send $send_id"),
$send_id = (int)$matches[1];
$member_id = (int)$matches[2];
$provided_hash = trim($matches[3]);
$real_hash = md5("bounce check for $member_id in send $send_id");
if($provided_hash == $real_hash){
$sql = "UPDATE "._DB_PREFIX."newsletter_member SET `status` = 4, bounce_time = '".time()."' WHERE `member_id` = '".$member_id."' AND send_id = '".$send_id."' AND `status` = 3 LIMIT 1";
query($sql);
imap_delete($mbox, $overview->msgno);
}else{
// bad hash, report.
}
}
unlink($tmp_file);
}
imap_expunge($mbox);
imap_close($mbox);
}
}
Thanks in advance!!
There's no PECL replacement for imap extension. If you dare, you can write one in PHP but that would be quite ineffective though. Alternative approach would be (assuming they are immune to customer's requests) to turn "GoDaddy" into "GoAwayDaddy" and change ISP to one who do not block this, quite elementary extension.
This one works on godaddy shared hosting:
http://www.phpclasses.org/package/4014-PHP-Retrieve-and-delete-messages-from-a-POP3-mailbox.html
And this one works too: http://framework.zend.com/manual/1.12/en/zend.mail.html
function __autoload($class_name) {
include $class_name . '.php';
}
include_once 'Zend/Mail/Storage/AbstractStorage.php';
include_once 'Zend/Mail/Storage/Pop3.php';
$mail = new Zend\Mail\Storage\Pop3(array('host' => '$host',
'user' => '$user',
'password' => '$password'));
echo $mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
echo "Mail from '{$message->from}': {$message->subject}\n</br>";
echo $message->getContent() . "</br>";
}

PHP Displaying unread mail count

I am using php imap class.
In my box I have a lot of mail, but with this script I would retrieve only the unreaded mail.
How can I do it?
if ($mbox=imap_open( "{" . $mailserver . ":" . $port . "}INBOX", $user, $pass ))
{
echo "Connected\n";
} else { exit ("Can't connect: " . imap_last_error() ."\n"); echo "FAIL!\n"; };
if ($hdr = imap_check($mbox)) {
$msgCount = $hdr->Nmsgs;
echo "Ci sono ".$msgCount." mail";
} else {
echo "Failed to get mail";
}
If I do
$overview=imap_fetch_overview($mbox,"1:$msgCount",0);
the script load to an infinity time.
The imap_search UNSEEN solution is not good because pop3 don't use this flag.
So how can I do??????
Thanks a lot.
There is two way you can follow:
1. Looping through the messages
$count = imap_num_msg($connection);
for($msgno = 1; $msgno <= $count; $msgno++) {
$headers = imap_headerinfo($connection, $msgno);
if($headers->Unseen == 'U') {
... do something ...
}
}
2. Using imap_search
There's a flag called UNSEEN which you can use to search for the unread emails. You would call the imap_search function with the UNSEEN flag like so:
$result = imap_search($connection, 'UNSEEN');
If you need to combine this with more search flags, for example searching for messages from me#example.com, you could do this:
$result = imap_search($connection, 'UNSEEN FROM "me#example.com"');
For a complete list of the available flags, refer to the criteria section of the imap_search manual page on the PHP website (www.php.net/imap_search)
Source: http://www.electrictoolbox.com/php-imap-unread-messages/
This was a tough one on Google: php imap unread
The first result:
http://www.electrictoolbox.com/php-imap-unread-messages/
There's a flag called UNSEEN which you can use to search for the unread emails. You would call the imap_search function with the UNSEEN flag like so:
view sourceprint?
$result = imap_search($connection, 'UNSEEN');
If you need to combine this with more search flags, for example searching for messages from me#example.com, you could do this:
view sourceprint?
$result = imap_search($connection, 'UNSEEN FROM "me#example.com"');
For a complete list of the available flags, refer to the criteria section of the imap_search manual page on the PHP website (www.php.net/imap_search)
Edit I had read this originally as IMAP. #fail.
Google: php pop3 unread
2nd link:
function CountUnreadMails($host, $login, $passwd) {
$mbox = imap_open("{{$host}/pop3:110}", $login, $passwd);
$count = 0;
if (!$mbox) {
echo "Error";
} else {
$headers = imap_headers($mbox);
foreach ($headers as $mail) {
$flags = substr($mail, 0, 4);
$isunr = (strpos($flags, "U") !== false);
if ($isunr)
$count++;
}
}
imap_close($mbox);
return $count;
}

How to remove an email message in Maildir from PHP?

I'm going crazy with a little problem with Maildir and PHP.
I need to check the APACHE_RUN_USER's Maildir and parse delivery-status messages.
The problem removing message after reading; i noticed that Zend_Mail_Storage_Maildir->removeMessage() is still a stub.
try {
$mailbox = new Zend_Mail_Storage_Maildir( array('dirname' => '/home/' . $_ENV['APACHE_RUN_USER'] . '/Maildir/') );
foreach ($mailbox as $id => $message) {
// seen flag
if ($message->hasFlag(Zend_Mail_Storage::FLAG_SEEN)) { continue; }
//get the unique id
$uniqueid = $mailbox->getUniqueId($id);
//obtain message headers
$headers = $message->getHeaders();
//check if the original message was sent from this app and is a delivery-status
$result = strpos($message, $id_header);
if($result === false) { echo '1 mail skipped: ' . $uniqueid . '. <br />'; continue; }
$result = strpos($headers['content-type'], 'delivery-status');
//if no skip to the next mail
if($result === false) { echo '1 mail skipped: ' . $uniqueid . '. <br />'; continue; }
// if everything it's ok process it.
// clear results
$data = array();
// foreach line of message
foreach( preg_split('/(\r?\n)/', $message) as $line ){
//clear results
$matches = array();
//perform matches on textlines
if( preg_match('/^(.+)\:\s{0,1}(.+)$/', $line, $matches) ) {
//grab intrested headers
foreach( array('Action', 'Status', 'Remote-MTA', 'Diagnostic-Code', $id_header) as $header) {
if($matches[1] == $header) $data[$header] = $matches[2];
}
}
}
// *** I NEED TO DROP THE MESSAGE HERE ***
// not working code ***
$currentmessageid = $mailbox->getNumberByUniqueId($uniqueid);
$mailbox->removeMessage($currentmessageid);
// *** I NEED TO DROP THE MESSAGE HERE ***
// print out results
echo '<pre class="email">';
print_r( $data );
echo '</pre>';
}
} catch (Exception $e) {
echo $e;
}
How can I remove it by hand? Some workarounds?
Thanks.
Sorry , its not implemented yet !
check out issue tracker http://framework.zend.com/issues/browse/ZF-9574
its open issue till today but some comment might be helpful :
In order to delete an email from a
maildir or mbox storage one must use:
Zend_Mail_Storage_Writable_Maildir or
Zend_Mail_Storage_Writable_Mbox
There are historical reasons for this
and they should be addressed and
standardised. For now the above
classes must be used or an exception
will be thrown with a message that is
a bit misleading.
Please refer to:
http://framework.zend.com/issues/browse/ZF-9574
for more details.
In order of tawfekov answer I solved as follow:
Opening mailbox:
$mailbox = new Zend_Mail_Storage_Writable_Maildir( array('dirname' => '/home/' . $_ENV['APACHE_RUN_USER'] . '/Maildir/') );
Processing mail code:
foreach ($mailbox as $id => $message) {
$uniqueid = $mailbox->getUniqueId($id);
/* ... mail processing code ... */
// mark as read
$currentmessageid = $mailbox->getNumberByUniqueId($uniqueid);
$mailbox->setFlags($currentmessageid, array(Zend_Mail_Storage::FLAG_SEEN));
// or uncomment to delete it
//$mailbox->removeMessage($currentmessageid);
}

Categories