Get attachment from mail using php - php

I need code to monitor my mail inbox and forward the mails with an attachment to another email address. I used the code below to fetch the attachments from the received messages. But I'm getting an error "Notice: Undefined property: stdClass::$disposition in C:\wamp\www\mail\c.php on line 60"
Here is my code
<?php
$host = '{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}inbox';
$login = 'AAAA#CCC.com';
$password = 'XXXXXXX';
$savedirpath = "../mail";
$type = 'ReadAttachment';
$obj = new $type;
$obj->getdata($host,$login,$password,$savedirpath,$delete_emails=false);
class ReadAttachment{
function getdecodevalue($message,$coding) {
switch($coding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message=imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
function getdata($host,$login,$password,$savedirpath,$delete_emails=false) {
// make sure save path has trailing slash (/)
//print_r("test");
$savedirpath = str_replace('\\', '/', $savedirpath);
if (substr($savedirpath, strlen($savedirpath) - 1) != '/') {
$savedirpath .= '/';
}
$mbox = imap_open ($host, $login, $password) or die("can't connect: " . imap_last_error());
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";
//print_r($message);
$emails = imap_search($mbox,'ALL');
foreach($emails as $email_number) {
$structure = imap_fetchstructure($mbox, $email_number , FT_UID);
$parts = $structure->parts;
$fpos=2;
for($i = 1; $i < count($parts); $i++) {
$message["pid"][$i] = ($i);
$part = $parts[$i];
if($part->disposition == "ATTACHMENT") {
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext=$part->subtype;
$params = $part->dparameters;
$filename=$part->dparameters[0]->value;
$mege="";
$data="";
$mege = imap_fetchbody($mbox,$email_number,$fpos);
$filename="$filename";
$fp=fopen($savedirpath.$filename,"w");
$data=$this->getdecodevalue($mege,$part->type);
//print_r($data);
fputs($fp,$data);
fclose($fp);
$fpos+=1;
}
}
}
// imap_expunge deletes all tagged messages
imap_close($mbox);
}
}
Thanks to the author, but I couldn't get any help further.
I'm getting an error "Notice: Undefined property: stdClass::$disposition in C:\wamp\www\mail\c.php on line 60"
This exactly point out the line if($part->disposition == "ATTACHMENT").
Please provide me with a solution.
I am new to php, struggling to write this mail function,,
Thanks in advance :-)

You need to check if $disposition exists first:
if((isset($part->disposition))&&($part->disposition == "ATTACHMENT"))

Related

Sometimes get the attachment. sometimes not! using imap

i have a script to download all pdf file and save it in a library...
im using gmail account.. Imap is enabled;
using centOS 5.11, openssl version: 1.0.1g:
Why sometimes it works.. and why sometimes wont and have a error!
error says
PHP Warning: imap_open(): Couldn't open stream {imap.gmail.com:993/imap/ssl}INBOX
No such host as imap.gmail.comPHP Notice: Unknown: No such host as imap.gmail.com (errflg=2)
this is the code:
<?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'xxxxxx#gmail.com';
$password = 'password';
$savedirpath = "/myLibrary";
$type = 'ReadAttachment';
$obj = new $type;
$obj->getdata($hostname ,$username ,$password,$savedirpath);
class ReadAttachment
{
function getdecodevalue($message,$coding) {
switch($coding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message=imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
function getdata($hostname ,$username ,$password,$savedirpath) {
$savedirpath = str_replace('\\', '/', $savedirpath);
if (substr($savedirpath, strlen($savedirpath) - 1) != '/') {
$savedirpath .= '/';
}
$mbox = imap_open ($hostname , $username , $password) or die("can't connect: " . imap_last_error());
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";
$MC = imap_check($mbox);
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
$jk = 1;
foreach ($result as $overview) {
$date= strtotime($overview->date);
$unixDate = date("YmdHis", $date);
$from= $overview->from;
$structure = imap_fetchstructure($mbox, $jk);
$parts = (isset($structure->parts) ? $structure->parts : false);
$fpos=2;
for($i = 1; $i < count($parts); $i++) {
$message["pid"][$i] = ($i);
$part = $parts[$i];
if($part->disposition == "ATTACHMENT") {
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext=$part->subtype;
$params = $part->dparameters;
$filename=$part->dparameters[0]->value;
$mege="";
$data="";
$mege = imap_fetchbody($mbox,$jk,$fpos);
$filename="$filename";
$extension=pathinfo($filename);
$file_extension = $extension['extension'];
if($file_extension === "pdf")
{
$new_filename = $filename;
$fp=fopen($savedirpath.$new_filename,'w');
$data=$this->getdecodevalue($mege,$part->type);
fputs($fp,$data);
fclose($fp);
$fpos+=1;
}
}
} imap_delete($mbox,$jk);
$jk++;
}
imap_expunge($mbox);
imap_errors() ;
imap_close($mbox);
}
}
?>

how to rename the attachment file from from email using php?

I need help,
for example: the attachment name from my message inbox is sample.pdf,
I have an php script to download the attachment!
now my problem is to rename the attachment from inbox using php
i want to make php script that automatically change the attachment name(sample.pdf) into; ahm let say rename it into the subject of the message... so it become subject.pdf...
<?php $hostname = '{xxxxxxpop3/notls}INBOX';
$username = 'xxx#gmail.com';
$password = 'password';
$savedirpath = "/root/Fax";
$type = 'ReadAttachment';
$obj = new
$type;
$obj->getdata($hostname, $username, $password, $savedirpath, $delete_emails = false);
class ReadAttachment
{
function getdecodevalue ($message, $coding)
{
switch ($coding)
{
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
function getdata ($hostname, $username, $password, $savedirpath, $delete_emails = false)
{
// make sure savepath has trailing slash(/)
$savedirpath = str_replace('\\', '/', $savedirpath);
if (substr($savedirpath, strlen($savedirpath) - 1) != '/')
{
$savedirpath .= '/';
}
$mbox = imap_open($hostname, $username, $password) or die("can't connect: " . imap_last_error());
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";
for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++)
{
$structure = imap_fetchstructure($mbox, $jk, FT_UID);
$parts = (isset($structure->parts) ? $structure->parts : false);
$fpos = 2;
for ($i = 1; $i < count($parts); $i++)
{
$message["pid"][$i] = ($i);
$part = $parts[$i];
if ($part->disposition == "ATTACHMENT")
{
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext = $part->subtype;
$params = $part->dparameters;
$filename = $part->dparameters[0]->value;
$mege = "";
$data = "";
$mege = imap_fetchbody($mbox, $jk, $fpos);
$filename = "$filename";
$fp = fopen($savedirpath . $filename, 'w');
$data = $this->getdecodevalue($mege, $part->type);
fputs($fp, $data);
fclose($fp);
$fpos += 1;
}
}
if ($delete_emails)
{
// imap_delete tags a message for deletion
imap_delete($mbox, $jk);
}
} // imap_expunge deletes all tagged messages if ($delete_emails) { imap_expunge($mbox); }
imap_close($mbox);
}
}
?>
Well you set the filename here:
$fp = fopen($savedirpath . $filename, 'w');
so you just need to change the $filename to your desired value

imap "delete" message after downloading using php?

Downloading attachment was working... but the delete wasn't?
Can anyone tell me whats wrong and how to make it work?
<?php $hostname = '{xxxxxxpop3/notls}INBOX'; $username = 'xxx#gmail.com'; $password = 'password';
$savedirpath = "/root/Fax"; $type = 'ReadAttachment'; $obj = new $type; $obj->getdata($hostname, $username, $password, $savedirpath, $delete_emails = false);
class ReadAttachment {
function getdecodevalue ($message, $coding)
{
switch ($coding)
{
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
function getdata ($hostname, $username, $password, $savedirpath, $delete_emails = false)
{
// make sure savepath has trailing slash(/)
$savedirpath = str_replace('\\', '/', $savedirpath);
if (substr($savedirpath, strlen($savedirpath) - 1) != '/')
{
$savedirpath .= '/';
}
$mbox = imap_open($hostname, $username, $password) or die("can't connect: " . imap_last_error());
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";
for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++)
{
$structure = imap_fetchstructure($mbox, $jk, FT_UID);
$parts = (isset($structure->parts) ? $structure->parts : false);
$fpos = 2;
for ($i = 1; $i < count($parts); $i++)
{
$message["pid"][$i] = ($i);
$part = $parts[$i];
if ($part->disposition == "ATTACHMENT")
{
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext = $part->subtype;
$params = $part->dparameters;
$filename = $part->dparameters[0]->value;
$mege = "";
$data = "";
$mege = imap_fetchbody($mbox, $jk, $fpos);
$filename = "$filename";
$fp = fopen($savedirpath . $filename, 'w');
$data = $this->getdecodevalue($mege, $part->type);
fputs($fp, $data);
fclose($fp);
$fpos += 1;
}
}
if ($delete_emails)
{
// imap_delete tags a message for deletion
imap_delete($mbox, $jk);
}
} // imap_expunge deletes all tagged messages if ($delete_emails) { imap_expunge($mbox); }
imap_close($mbox);
} }
?>
add
imap_expunge($jk);
after
imap_delete($mbox, $jk);
if it doesn't work try imap_errors to see whats going on.

IMAP or POP3 server implemented in PHP

Is there any available implementation of POP3/IMAP server in PHP?
I am handling my e-mail service using sendgrid. I am going to store the messages on my server using files/db/whatever and now I'd like to provide full POP3 or IMAP (preferable) access for my users to their mailbox. Is there such implementation in PHP? Or is there any other possibility to run POP3/IMAP in the distributed environment of Windows Azure (assuming I have the mailboxes stored in shared blobs/tables/db)?
Well, just to show that it is in fact possible to write a POP3 server in PHP, here it is. The server does no authentication--or pretty much anything else. It just keep sending the same message over and over. But it works. Thunderbird was able to retrieve messages from it. Totally useless, but sort of cool.
My setup is Apache 2 on Windows with PHP 5.2.
<?php
// echo something so fopen() would return
header("Content-type: text/plain");
echo "OK\n";
flush();
// listen for incoming connection
$listen_socket = socket_create_listen(110, 1);
$r = $w = $e = array($listen_socket);
$n = socket_select($r, $w, $e, 120);
$client_socket = ($n == 1) ? socket_accept($listen_socket) : null;
socket_close($listen_socket);
// spawn copy of myself
$internal_url = "http://{$_SERVER['HTTP_HOST']}:{$_SERVER['SERVER_PORT']}{$_SERVER['SCRIPT_NAME']}";
$stream_context_options = array (
'http' => array (
'method' => 'GET',
'timeout' => 1
)
);
$context = stream_context_create($stream_context_options);
if($f = fopen($internal_url, "rb", 0, $context)) {
fclose($f);
}
if(!$client_socket) {
// timed out
exit;
}
// start handling the session
$read_buffer = "";
$write_buffer = "+OK POP3 server ready\r\n";
$active = true;
$messages = array(
"From: webmaster#example.com\r\nSubject: This is a test\r\n\r\nHello world!\r\n"
);
$idle_start = time();
while(true) {
$r = $w = $e = array($client_socket);
$n = socket_select($r, $w, $e, 60);
if($n) {
if($r) {
// read from the socket
$read_buffer .= socket_read($client_socket, 128);
$idle_start = time();
}
if($w) {
if($write_buffer) {
// write to the socket
$written = socket_write($client_socket, $write_buffer);
$write_buffer = substr($write_buffer, $written);
$idle_start = time();
} else if($active) {
$now = time();
$idle_time = $now - $idle_start;
if($idle_time > 10) {
// exit if nothing happened for 10 seconds
break;
} else if($idle_time > 2) {
// start napping when the client is too slow
sleep(1);
}
} else {
break;
}
}
if($e) {
break;
}
if($read_buffer) {
if(preg_match('/(.*?)(?:\s+(.*?))?[\r\n]+/', $read_buffer, $matches)) {
$read_buffer = substr($read_buffer, strlen($matches[0]));
$command = $matches[1];
$argument = $matches[2];
switch($command) {
case 'USER':
$username = $argument;
$write_buffer .= "+OK $username is welcome here\r\n";
break;
case 'PASS':
$message_count = count($messages);
$write_buffer .= "+OK mailbox has $message_count message(s)\r\n";
break;
case 'QUIT':
$write_buffer .= "+OK POP3 server signing off\r\n";
$active = false;
break;
case 'STAT':
$message_count = count($messages);
$mailbox_size = 0;
foreach($messages as $message) {
$mailbox_size += strlen($message);
}
$write_buffer .= "+OK $message_count $mailbox_size\r\n";
break;
case 'LIST':
$start_index = (int) $argument;
$message_count = count($messages) - $start_index;
$total_size = 0;
for($i = $start_index; $i < count($messages); $i++) {
$total_size += strlen($messages[$i]);
}
$write_buffer .= "+OK $message_count messages ($total_size octets)\r\n";
for($i = $start_index; $i < count($messages); $i++) {
$message_id = $i + 1;
$message_size = strlen($messages[$i]);
$write_buffer .= "$message_id $message_size\r\n";
}
$write_buffer .= ".\r\n";
break;
case 'RETR':
$message_id = (int) $argument;
$message = $messages[$message_id - 1];
$message_size = strlen($message);
$write_buffer .= "+OK $message_size octets\r\n";
$write_buffer .= "$message\r\n";
$write_buffer .= ".\r\n";
break;
case 'DELE':
$write_buffer .= "+OK\r\n";
break;
case 'NOOP':
$write_buffer .= "+OK\r\n";
break;
case 'LAST':
$message_count = count($messages) - $start_index;
$write_buffer .= "+OK $message_count\r\n";
break;
case 'RSET':
$write_buffer .= "+OK\r\n";
break;
default:
$write_buffer .= "-ERR Unknown command '$command'\r\n";
}
}
}
} else {
break;
}
}
?>

PHP IMAP function to detach attachment and save to a directory

I'm trying to use IMAP function to detach an attachment received from inbox and save into the server directory specified.
I am doing this for all UNSEEN messages but the problem is that it only does for one message only.
Below is the code (I deleted $host,$login,$password variables for obvious reasons):
$type = 'ReadAttachment';
$obj = new $type;
$obj->getdata($host,$login,$password,$savedirpath,$delete_emails=false);
class ReadAttachment
{
function getdecodevalue($message,$coding) {
switch($coding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
function getdata($host,$login,$password,$savedirpath,$delete_emails=false, $read_type="UNSEEN") {
// make sure save path has trailing slash (/)
//print_r("test");
$savedirpath = str_replace('\\', '/', $savedirpath);
if (substr($savedirpath, strlen($savedirpath) - 1) != '/') {
$savedirpath .= '/';
}
$mbox = imap_open ($host, $login, $password) or die("can't connect: " . imap_last_error());
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";
//print_r($message);
$emails = imap_search($mbox,$read_type) or die(print_r(imap_last_error()));
print_r($emails);
$e = imap_search($mbox,$read_type, SE_UID) or die(print_r(imap_last_error()));
print_r($e);
$i=0;
foreach($emails as $email_number) {
$structure = imap_fetchstructure($mbox, $e[$i] , FT_UID) or die(print_r(imap_last_error()));
$parts = $structure->parts;
$fpos=2;
for($i = 1; $i < count($parts); $i++) {
$message["pid"][$i] = ($i);
$part = $parts[$i];
if($part->disposition == "attachment") {
$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
$message["subtype"][$i] = strtolower($part->subtype);
$ext=$part->subtype;
$params = $part->dparameters;
$filename=$part->dparameters[0]->value;
$mege="";
$data="";
$mege = imap_fetchbody($mbox,$email_number,$fpos);
$filename="$filename";
$fp=fopen($savedirpath.$filename,"w");
$data=$this->getdecodevalue($mege,$part->type);
//print_r($mege);
fputs($fp,$data);
fclose($fp);
$fpos+=1;
}
}
++$i;
}
// imap_expunge deletes all tagged messages
imap_close($mbox);
}
}
Is there something that I could change above?
I'm not sure whether this is the cause of the problem, or if I even understood your code correctly. However I think your $i=0 needs to go inside the foreach loop, and you need to lose the ++$i at the end.
Let's go through it. First, you set $i=0. foreach gets the first message and enters the for loop, which iterates over incrementing values of $i. Let's say that $i is set to 4 when the for loop ends. At that point, ++$i sets it to 5. The foreach iteration ends and the next email should be processed. But this does not happen because $i is still 5, so when you do:
$structure = imap_fetchstructure($mbox, $e[$i] , FT_UID)
You are picking the wrong email.
Actually looking at the script I think he's using $i in 2 places incorrectly. the $i within the foreach should be a different variable.
for the $structure variable he should use the $i as expected ...
but the mail parts should use a separate variable (I used $p)
i know this is an old post, but it helped me a bit.

Categories