PHP imap_functions get attachments OLE format - php

It's possible get email from gmail account, but only get emails with OLE attachments?
I'm using this code:
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '';
$password = '';
try {
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$structureb = imap_fetchbody($inbox, $email_number,0);
echo "<h1>imap_fetchstructure</h1><pre>";
print_r($structureb);
echo "</pre>";
/* get information specific to this email */
$structureb = imap_body($inbox, $email_number,0);
echo "<h1>imap_fetchstructure</h1><pre>";
print_r($structureb);
echo "</pre>";
/* get information specific to this email */
$structure = imap_fetchstructure($inbox, $email_number,0);
echo "<h1>imap_fetchstructure</h1><pre>";
print_r($structure);
echo "</pre>";
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
echo "<h1>imap_fetch_overview</h1><pre>";
print_r($overview);
echo "</pre>";
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
echo "<h3>final</h3><pre>";
print_r($attachments);
echo "</pre>";
/* output the email header information */
$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
/* output the email body */
$output.= '<div class="body">'.$message.'</div>';
echo $output;
break;
}
echo $output;
}
/* close the connection */
imap_close($inbox);
} catch (Exception $e) {
throw new Exception("Error Processing Request = " . $e->getMessage(), 1);
}
But when i search in this several functions something that indicate is a OLE attachment i can't found anything.
Exist some way to get emails with OLE attachments?

Related

how can i download all files attachments in php?

i'm trying for my program to download all file attachments, but for some reason it doesn't download all of them only downloads a certain file attachment. This is the code:
<?php
set_time_limit(3000);
$hostname = '{someoutlookemail.outlook.com:993/imap/ssl}INBOX';
$username = 'someoutlookemail#outlook.com';
$password = 'apass';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
$max_emails = 16;
/* if emails are returned, cycle through each... */
if($emails) {
$count = 1;
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1.1);
$structure = imap_fetchstructure($inbox,$email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
/* prefix the email number to the filename in case two emails
* have the attachment with the same file name.
*/
$fp = fopen("./" . $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
if($count++ >= $max_emails) break;
/* output the email header information */
$output.= '<p><div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<p>Subject: <span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<p>From: <span class="from">'.$overview[0]->from.'</span>';
$output.= '<p>Date: <span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
/* output the email body */
$output.= '<p>Message:<div class="body">'.$message.'';
$output.= '<p>attachment:'.$filename.'';
$output.= '<table><tr><hr size="1" width="100%%" noshade color="black" ></tr></table>';
}
echo $output;
}
/* close the connection */
imap_close($inbox);
?>
whats wrong ? i tried to check all of my code and i dont understand why it only downloads some, i'm downloading the same type of file for now (.xml), one of them downloads and the other doesn't, the one who downloads has 1mb size and the other one 600kb, please help, i'have searched everywhere, and i can't find a solution.
Your script it working fine for me, all the files are being download. The only problem is that is not showing correctly, you should iterate on the attachments, when you echo the output. Something like this
<?php
set_time_limit(3000);
/* try to connect */
/* if emails are returned, cycle through each... */
if($emails) {
$count = 1;
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1.1);
$structure = imap_fetchstructure($inbox,$email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $key=>$attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
/* prefix the email number to the filename in case two emails
* have the attachment with the same file name.
*/
$fp = fopen("./" . $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
$attachments[$key]['filename'] = $filename;
}
}
if($count++ >= $max_emails) break;
/* output the email header information */
$output.= '<p><div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<p>Subject: <span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<p>From: <span class="from">'.$overview[0]->from.'</span>';
$output.= '<p>Date: <span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
/* output the email body */
$output.= '<p>Message:<div class="body">'.$message.'';
foreach ($attachments as $attachment) {
$output.= '<p>attachment:'.$attachment['filename'].'';
}
$output.= '<table><tr><hr size="1" width="100%%" noshade color="black" ></tr></table>';
}
echo $output;
}
/* close the connection */
imap_close($inbox);
?>

How to fetch the gmail message body with php and imap

I am using IMAP to retrieve the gmail message , actually the messages are coming from a data-logger after a continuous time of 1 hour interval when i am trying to fetching the email body it is showing the encoded body like "VVNSOlNpdGUwMV82LDAsNDksVHJ5Q291bnQ9MSxGVFBTdWNjZXNzPS0x " and the orignal text is "USR:Site01_6,0,49,TryCount=1,FTPSuccess=-1",
if i copy the text manualy and sent an email from my other email then i can fetching this as same as orignal , can't understanding where is the problem ,, here is the code i am using for this ,
public function fetch_gmail_inbox()
{
$res=array();
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'clnvsdty#gmail.com';
$password = 'Solarisgr8';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message =imap_fetchbody($inbox,$email_number,1);
$structure = imap_fetchstructure($inbox,$email_number);
if($structure->parts[0]->encoding == 3 ||$structure->encoding == 3 )
{
$message=imap_base64($message);
}
if($structure->parts[0]->encoding == 4 ||$structure->encoding == 4)
{
$message = imap_qprint($message);
}
$message2= quoted_printable_decode(imap_fetchbody($inbox,$email_number,0));
$date=explode(':',$message2);
$date2= date('d-m-Y h:i:s',strtotime($date[8].':00:00'));
$sub=$string = preg_replace('/\s+/', '', $overview[0]->subject);
$tomatch=preg_replace('/\s+/', '', "USR:Site01_Comms Complete");
if(strcmp($sub,$tomatch)==0)
{
$res['date']=$date2;
$res['body']=$message;
}
}
return $res;
}
/* close the connection */
imap_close($inbox);
}
any help will be appreciated
try using this
function fetch_gmail_inbox($check='UNSEEN')
{
$res=array();
/* connect to gmail */
$hostname = '{mail.enlighten-energy.net:143/imap/novalidate-cert}INBOX';
$username = Yii::app()->getModule('user')->get_config('datalogger_email');
$password = Yii::app()->getModule('user')->get_config('datalogger_email_pwd');
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,$check);
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
rsort($emails);
/* for every email... */
$data3=array();
foreach($emails as $email_number)
{
//print_r($email_number); echo "#####";
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
//echo "<pre>";print_r($overview);
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1));
$structure = imap_fetchstructure($inbox,$email_number);
$attachments = array();
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 4 = QUOTED-PRINTABLE encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 3 = BASE64 encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
$data2=array();
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$filename=str_replace('/','',$filename);
$filename="uploads/gmail_attachment/".$email_number . "-" . $filename;
$fp = fopen($filename, "w+");
if(fwrite($fp, $attachment['attachment']))
{
$data=self::fetch_xls_data($email_number,$filename);
}
fclose($fp);
}
$data2[$email_number]=$data;
unlink($filename);
}
$data3[$email_number]=$data2[$email_number];
}
return $data3;
}
/* close the connection */
imap_close($inbox);
//return $data;
}

How to fetch all unread mail with attachment as an array ? i am using following code

I am trying to use this code, but I don't understand how we fetch the attachment with the sender's email . This is my code, and I tried so many times with different-2 code but yet I get no solutions.
public function myresume(&$response)
{
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'My gmail username';
$password = 'password';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
$output = '';
rsort($emails);
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
$output.= '<div class="body">'.$message.'</div>';
}
echo $output ;
}
imap_close($inbox);
}
Try this way to get unseen email and store in any folder
$server = '{imap.gmail.com:993/imap/ssl}INBOX';
$login = 'username';
$password = 'password';
/* try to connect */
$connection = imap_open($server,$login,$password) or die('Cannot connect to your sever: ' . imap_last_error());
/*get only unseen mail from inbox*/
$result = imap_search($connection, 'UNSEEN');
$max_emails = 1;
/* if any emails found, iterate through each email */
if($emails) {
$count = 1;
/* put the newest emails on top */
rsort($emails);
$attachments = array();
/* for every email... */
foreach($emails as $email_number)
{
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 4 = QUOTED-PRINTABLE encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 3 = BASE64 encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
}
imap_close($inbox);
/*store mail attachments to locally*/
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename))
$filename = $attachment['filename'];
if(empty($filename))
$filename = time() . ".dat";
$fp = fopen($path." ".$email_number . "-" . $filename, "w+");
$csvFileName=$path." ".$email_number . "-" . $filename;
fwrite($fp, $attachment['attachment']);
fclose($fp);
$array=$fields=array();
$i=0;
}
}
}
You can use imap_fetchstructure to understand the mail structure and fetch the attachments. Below is a example copied from http://www.php.net/manual/en/function.imap-fetchstructure.php
(code to parse and decode all types of messages, including attachments.)
<?php
function getmsg ($mbox, $mid)
{
// input $mbox = IMAP stream, $mid = message id
// output all the following:
global $charset, $htmlmsg, $plainmsg, $attachments;
$htmlmsg = $plainmsg = $charset = '';
$attachments = array();
// HEADER
$h = imap_header($mbox, $mid);
// add code here to get date, from, to, cc, subject...
// BODY
$s = imap_fetchstructure($mbox, $mid);
if (! $s->parts) // simple
getpart($mbox, $mid, $s, 0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0 => $p)
getpart($mbox, $mid, $p, $partno0 + 1);
}
}
function getpart ($mbox, $mid, $p, $partno)
{
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg, $plainmsg, $charset, $attachments;
// DECODE DATA
$data = ($partno) ? imap_fetchbody($mbox, $mid, $partno) : // multipart
imap_body($mbox, $mid); // simple
// Any part may be encoded, even plain text messages,
// so check everything.
if ($p->encoding == 4)
$data = quoted_printable_decode($data);
elseif ($p->encoding == 3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename']) ? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$attachments[$filename] = $data; // this is a problem if two files have
// same name
}
// TEXT
if ($p->type == 0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype) == 'plain')
$plainmsg.
trim($data) . "\n\n";
else
$htmlmsg. =
$data . "<br><br>";
$charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type == 2 && $data) {
$plainmsg. =
$data . "\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0 => $p2)
getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1)); // 1.2, 1.2.1, etc.
}
}
?>

Body content does not display properly when fetch mail through gmail using imap in php

I am using this code for display body content and attachment. Its working properly everything only body content is not display properly.
<?php
ini_set('max_execution_time', 0);
require_once('front_include/connect.inc.php');
$mail = new imap_mail();
$configuration_data = $mail->get_configuration();
$hostname = $configuration_data['host_name'];
$username = $configuration_data['user_name'];
$password = $configuration_data['password'];
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
$m=1;
foreach($emails as $email_number) {
/* output the email body */
$message = imap_fetchbody($inbox,$email_number,2);
//$output.= '<div class="body">'.utf8_encode(quoted_printable_decode($message)).'</div>';
// start for detail
$header = imap_header($inbox, $email_number);
//print_r($header);
$email[$m]['from'] = $header->from[0]->mailbox.'#'.$header->from[0]->host;
$email[$m]['fromaddress'] = $header->from[0]->personal;
$email[$m]['to'] = $header->to[0]->mailbox;
$email[$m]['subject'] = $header->subject.'</br>';
$email[$m]['message_id'] = $header->Msgno;
$email[$m]['date'] = $header->MailDate;
// Start for attachment
$structure = imap_fetchstructure($inbox, $email_number);
$message = imap_fetchbody($inbox,$email_number,2);
echo $message.'First';
$message2 = imap_fetchbody($inbox,$email_number,1.2);
echo $message2.'Second';
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message1 = imap_fetchbody($inbox,$email_number,2);
if($part->encoding == 3) {
$message1 = imap_base64($message1);
} else if($part->encoding == 1) {
$message1 = imap_8bit($message1);
} else {
$message1 = imap_qprint($message1);
}
echo $message1.'Hello';
}
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/********* insert data in databse ***********/
$mail->mail_insert($email[$m]['from'],$email[$m]['fromaddress'],$email[$m]['to'],$email[$m]['subject'],$email[$m]['date'],$email[$m]['message_id'],$message);
$mail_id = mysql_insert_id();
/********* insert data in databse ***********/
foreach ($attachments as $key => $attachment) {
if($attachment['name'] != '')
{
$name = $header->Msgno.date('d-m-y').time().$attachment['name'];
$display_name = $attachment['name'];
$contents = $attachment['attachment'];
$mail->attachment_insert($header->Msgno,$mail_id,$display_name,$name);
file_put_contents($name, $contents);
}
}
$m++;
}
}
/* close the connection */
imap_close($inbox);
?>
Sometimes it display properly content using this code
$message = imap_fetchbody($inbox,$email_number,2);
But sometime its not working why this issue is creating.
I tried three 3 types of display body content but no one of display body content properly.
Can any one suggest me how i can display properly body content of message.
Please help me...
Thanks in Advance.
$message = imap_fetchbody($inbox,$email_number, 1.2);

PHP IMAP decoding messages

I have emails sent via base64 encoding and 8bit encoding. I was wondering how I could check the encoding of the message using imap_fetchstructure (been doing this for about two hours, so lost) and then decode it properly.
Gmail and Mailbox (app on iOS) are sending it as 8bit while Windows 8's Mail app is sending it as base64. Either way, I need to decode whether its 8bit or base64 by detecting what type of encoding it has used.
Using PHP 5.1.6 (yes, I should update, been busy).
I really have no code to show. This is all I have:
<?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails) {
$output = '';
rsort($emails);
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$struct = imap_fetchstructure($inbox, $email_number);
$output.= '<div class="toggle'.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
/* output the email body */
$output.= '<div class="body">'.$message.'</div>';
}
echo $output;
}
imap_close($inbox);
?>
imap_bodystruct() or imap_fetchstructure() should return this info to you. The following code should do exactly what you're looking for:
<?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails) {
$output = '';
rsort($emails);
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($inbox,$email_number,2);
if($part->encoding == 3) {
$message = imap_base64($message);
} else if($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_qprint($message);
}
}
$output.= '<div class="toggle'.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="from">From: '.utf8_decode(imap_utf8($overview[0]->from)).'</span>';
$output.= '<span class="date">on '.utf8_decode(imap_utf8($overview[0]->date)).'</span>';
$output.= '<br /><span class="subject">Subject('.$part->encoding.'): '.utf8_decode(imap_utf8($overview[0]->subject)).'</span> ';
$output.= '</div>';
$output.= '<div class="body">'.$message.'</div><hr />';
}
echo $output;
}
imap_close($inbox);
?>
You can look at this example.
Imap/Imap
Here's code snippet
switch ($encoding) {
# 7BIT
case 0:
return $text;
# 8BIT
case 1:
return quoted_printable_decode(imap_8bit($text));
# BINARY
case 2:
return imap_binary($text);
# BASE64
case 3:
return imap_base64($text);
# QUOTED-PRINTABLE
case 4:
return quoted_printable_decode($text);
# OTHER
case 5:
return $text;
# UNKNOWN
default:
return $text;
}
Returned Objects for imap_fetchstructure()
encoding (Body transfer encoding)
Transfer encodings (may vary with used library)
0 7BIT
1 8BIT
2 BINARY
3 BASE64
4 QUOTED-PRINTABLE
5 OTHER
$s = imap_fetchstructure($mbox,$mid);
if ($s->encoding==3)
$data = base64_decode($data);
I also faced this issue, and this is how I fixed
$structure = imap2_fetchstructure($connection, $messages);
if (!isset($structure->parts) || !is_array($structure->parts) || !isset($structure->parts[0])) {
$body = imap2_body($connection, $messages);
return base64_decode($body);
}
$part = $structure->parts[0];
$body = imap2_fetchbody($connection, $messages, '1');
if ($part->encoding == 3) {
return base64_decode($body);
}
if ($part->encoding == 1) {
return imap2_8bit($body);
}
return imap2_qprint($body);
// Best for reading attached file from e-mail as well as body of the mail
$hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
$username = 'xzy.xyz#xyz.com';
$password = '****************';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'SUBJECT "'.$subject.'"');
rsort($emails);
foreach ($emails as $key => $value) {
$overview = imap_fetch_overview($inbox,$value,0);
$message_date = new DateTime($overview[0]->date);
$date = $message_date->format('Ymd');
$message = imap_fetchbody($inbox,$value,2);
$structure = imap_fetchstructure($inbox, $value);
$attachments = [];
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $value, $i+1);
if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
}
imap_close($inbox);//Never forget to close the connection

Categories