Locate HTML and plain text using imap_fetchstructure - php

I want to locate the html and/or the plain text using the imap_fetchstructure.
I tried several solutions but the emails don't have always the same structure.
I'm actually using:
$message=imap_fetchbody($inbox, $number, "1.2.1");
if ($message== "") {
$message =imap_fetchbody($inbox, $number, "1.1");
}
if ($message== "") {
$message = imap_fetchbody($inbox, $number, "1");
}
$message = imap_qprint($body);
When trying this; the result is sometimes correct and sometimes returning The content of the attachements depending on the mail server.
So I want a solution based on Imap_fetchstructure.

I found an answer for my question:
function getBody($uid, $imap) {
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
switch ($structure->encoding) {
case 3: return imap_base64($text);
case 4: return imap_qprint($text);
default: return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct,
$prefix. ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure) {
$primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION",
"AUDIO", "IMAGE", "VIDEO", "OTHER");
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}

You can use like this to separate from html and plaintext:
$inbox = imap_open($hostName,$userName,$pwd) or die('Cannot connect (Allow gmail IMAP): ' . imap_last_error());
$emails = imap_search($inbox,'UNSEEN');
if($emails){
rsort($emails);
foreach($emails as $email_number){
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {// IF HTML
$part = $structure->parts[1];
$receivedEmailContent = imap_fetchbody($inbox,$email_number,2);
if($part->encoding == 3) {
$receivedEmailContent = imap_base64($receivedEmailContent);
} else if($part->encoding == 1) {
$receivedEmailContent = imap_8bit($receivedEmailContent);
} else {
$receivedEmailContent = imap_qprint($receivedEmailContent);
}
}else{//IF NOT HTML
$receivedEmailContent = imap_fetchbody($inbox,$email_number,1);
if($structure->type == 0){
$receivedEmailContent = imap_base64($receivedEmailContent);
}else{
$receivedEmailContent = imap_qprint($receivedEmailContent);
}
}
$receivedEmailContent = strip_tags($receivedEmailContent);
$header = imap_headerinfo ( $inbox, $email_number);
$receivedEmailTitle = $header->subject;
$receivedEmailSenderName = $header->from[0]->personal;
$receivedEmailSenderEmail = $header->from[0]->mailbox . "#" . $header->from[0]->host;
}
}
imap_close($inbox);

Related

Fetching email using PHP imap messes up inline embedded images

I made a webmail php class to fetch my domain's webmail.
Everything runs perfectly except that when the email has embedded images (like signatures), the images are fetched with CID in their src and also are treated as attachments.
<img src="cid:auto_cid_2093934881" />
So i end up with a broken source image (in its original place in the email body) and an attachment of the same image that actually works. But i don't need the image to be an attachment, i just want the images to be shown in their places.
Can anyone help me fix this class so it can fetch the images correctly?
Here's my code to get a single email:
<?php
$uid=mysql_real_escape_string($_GET['email_id']);
ini_set("max_execution_time",360);
/* connect to server */
$hostname = '{***.com:143/notls}INBOX';
$username = 'fadi#***.com';
$password = '*******';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to domain:' . imap_last_error());
$overview = imap_fetch_overview($inbox,$uid,0);
$header = imap_headerinfo($inbox, $uid);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$webmail = new Webmail();
$message = $webmail->getEmailBody($uid,$inbox);
$attachments = $webmail->extract_attachments($inbox,$uid);
$attach_hrefs = '';
if(count($attachments)!=0){
$target_dir = "emails/".$uid;
if (!is_dir($target_dir)) {
// dir doesn't exist, make it
mkdir($target_dir);
}
foreach($attachments as $at){
if($at[is_attachment]==1){
file_put_contents($target_dir.'/'.$at[filename], $at[attachment]);
$attach_hrefs .='<a target="new" href="'.$target_dir.'/'.$at[filename].'">'.$at[filename].'</a> ';
}
}
}
?>
Here's the webmail class:
<?php
class Webmail{
function getEmailBody($uid, $imap)
{
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false)
{
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
switch ($structure->encoding) {
case 3:
return imap_base64($text);
case 4:
return imap_qprint($text);
default:
return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure)
{
$primaryMimetype = ["TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"];
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
function extract_attachments($connection, $message_number) {
$attachments = array();
$structure = imap_fetchstructure($connection, $message_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($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']);
}
}
}
}
return $attachments;
}
}
?>
Thanks in advance.
Try bellow class for fetch mail body with inline image
Note See get_mail_body($body_type = 'html') method in class to that store mail body inline image to local server you need to change it as you directory layout.
I hope this help you.
$email_message = new Email_message();
$mailbody = $email_message->get_mail_body();
;
class Email_message {
public $connection;
public $messageNumber;
public $bodyHTML = '';
public $bodyPlain = '';
public $attachments;
public $getAttachments = true;
public function __construct($config_data = array()) {
$this->connection = $config_data['connection'];
$this->messageNumber = isset($config_data['message_no'])?$config_data['message_no']:1;
}
public function fetch() {
$structure = #imap_fetchstructure($this->connection, $this->messageNumber);
if(!$structure) {
return false;
}
else {
if(isset($structure->parts)){
$this->recurse($structure->parts);
}
return true;
}
}
public function recurse($messageParts, $prefix = '', $index = 1, $fullPrefix = true) {
foreach($messageParts as $part) {
$partNumber = $prefix . $index;
if($part->type == 0) {
if($part->subtype == 'PLAIN') {
$this->bodyPlain .= $this->getPart($partNumber, $part->encoding);
}
else {
$this->bodyHTML .= $this->getPart($partNumber, $part->encoding);
}
}
elseif($part->type == 2) {
$msg = new Email_message(array('connection' =>$this->connection,'message_no'=>$this->messageNumber));
$msg->getAttachments = $this->getAttachments;
if(isset($part->parts)){
$msg->recurse($part->parts, $partNumber.'.', 0, false);
}
$this->attachments[] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => '',
'data' => $msg,
'inline' => false,
);
}
elseif(isset($part->parts)) {
if($fullPrefix) {
$this->recurse($part->parts, $prefix.$index.'.');
} else {
$this->recurse($part->parts, $prefix);
}
}
elseif($part->type > 2) {
if(isset($part->id)) {
$id = str_replace(array('<', '>'), '', $part->id);
$this->attachments[$id] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => $this->getFilenameFromPart($part),
'data' => $this->getAttachments ? $this->getPart($partNumber, $part->encoding) : '',
'inline' => true,
);
} else {
$this->attachments[] = array(
'type' => $part->type,
'subtype' => $part->subtype,
'filename' => $this->getFilenameFromPart($part),
'data' => $this->getAttachments ? $this->getPart($partNumber, $part->encoding) : '',
'inline' => false,
);
}
}
$index++;
}
}
function getPart($partNumber, $encoding) {
$data = imap_fetchbody($this->connection, $this->messageNumber, $partNumber);
switch($encoding) {
case 0: return $data; // 7BIT
case 1: return $data; // 8BIT
case 2: return $data; // BINARY
case 3: return base64_decode($data); // BASE64
case 4: return quoted_printable_decode($data); // QUOTED_PRINTABLE
case 5: return $data; // OTHER
}
}
function getFilenameFromPart($part) {
$filename = '';
if($part->ifdparameters) {
foreach($part->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$filename = $object->value;
}
}
}
if(!$filename && $part->ifparameters) {
foreach($part->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$filename = $object->value;
}
}
}
return $filename;
}
function get_mail_body($body_type = 'html')
{
$mail_body = '';
if($body_type == 'html'){
$this->fetch();
preg_match_all('/src="cid:(.*)"/Uims', $this->bodyHTML, $matches);
if(count($matches)) {
$search = array();
$replace = array();
foreach($matches[1] as $match) {
$unique_filename = time().".".strtolower($this->attachments[$match]['subtype']);
file_put_contents("./uploads/$unique_filename", $this->attachments[$match]['data']);
$search[] = "src=\"cid:$match\"";
$replace[] = "src='".base_url()."/uploads/$unique_filename'";
}
$this->bodyHTML = str_replace($search, $replace, $this->bodyHTML);
$mail_body = $this->bodyHTML;
}
}else{
$mail_body = $this->bodyPlain;
}
return $mail_body;
}
}

Php Imap fetching emails

I have been trying to fetch email body with imap_fetchbody($stream, $msgno, $option)
but didn't success quite well.
Then I tried using imap_fetchstructure($stream, $msgno) and decode each types manually with their own subtypes like:-
1. Alternative
2. Related
3. Mixed
For the first two I can decode with something like this
**1. Alternative**
if ($structure->subtype == 'ALTERNATIVE') {
if (isset($structure->parts)) {
$body2 = imap_fetchbody($stream, $email_id, 2);
if ($body2 == null) {
$body2 = imap_fetchbody($stream, $email_id, 1);
}
$body = quoted_printable_decode($body2);
}
}
**2. Related**
if ($structure->subtype == 'RELATED') {
if (isset($structure->parts)) {
$parts = $structure->parts;
$i = 0;
$body2 = imap_fetchbody($stream, $email_id, 1.2);
if ($body2 == null) {
$body2 = imap_fetchbody($stream, $email_id, 1);
}
$body = quoted_printable_decode($body2);
foreach ($parts as $part) {
if ($parts[$i]) {
}
$i++;
if (isset($parts[$i])) {
if ($parts[$i]->ifid == 1) {
$id = $parts[$i]->id;
$imageid = substr($id, 1, -1);
$imageid = "cid:" . $imageid;
if ($parts[$i]->ifdparameters == 1) {
foreach ($parts[$i]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$filename = $object->value;
}
}
}
if ($parts[$i]->ifparameters == 1) {
foreach ($parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$name = $object->value;
}
}
}
$body = str_replace($imageid, $filename, $body);
}
}
}
}
}
But when it comes to mixed either I don't know or what am I suppose to do or where am I making mistake.
**3. mixed**
if ($structure->subtype == 'MIXED') {
if (isset($structure->parts)) {
$parts = $structure->parts;
// subtype = ALTERNATIVE
if ($parts[0]->subtype == 'ALTERNATIVE') {
if (isset($structure->parts)) {
$body2 = imap_fetchbody($stream, $email_id, 1.2);
if ($body2 == null) {
$body2 = imap_fetchbody($stream, $email_id, 1);
}
$body = quoted_printable_decode($body2);
}
}
// subtype = RELATED
if ($parts[0]->subtype == 'RELATED') {
if (isset($parts[0]->parts)) {
$parts = $parts[0]->parts;
$i = 0;
$body2 = imap_fetchbody($stream, $email_id, 1.1);
if ($body2 == null) {
$body2 = imap_fetchbody($stream, $email_id, 1);
}
$body = quoted_printable_decode($body2);
$name = "";
foreach ($parts as $part) {
if ($parts[0]) {
}
$i++;
if (isset($parts[$i])) {
if ($parts[$i]->ifid == 1) {
$id = $parts[$i]->id;
$imageid = substr($id, 1, -1);
$imageid = "cid:" . $imageid;
if ($parts[$i]->ifdparameters == 1) {
foreach ($parts[$i]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$filename = $object->value;
}
}
}
if ($parts[$i]->ifparameters == 1) {
foreach ($parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$name = $object->value;
}
}
}
}
$body = str_replace($imageid, $name, $body);
}
}
}
}
}
}
You forgot the subtype PLAIN. Also you have to decode it too
if ($parts[0]->subtype == 'PLAIN') {
if (isset($structure->parts)) {
$message2 = imap_fetchbody($stream, $email_id, 1);
$message = quoted_printable_decode(base64_decode($message2));
}
}

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);

Attachment sent as encoded text

I am trying to forward the attachment sin my email to another account automatically using this script and swift mailer library. Thing seems to be working for certain extent but the attachments are sent as encoded text. I wanted to send the attachments as it is. I am new to php and unable to figure out where the issue is. Please help me.
<?php
require_once 'lib/swift_required.php';
$hostname = '{imap.asd.com:993/imap/ssl}INBOX';
$username = 'abc#as.com';
$password = 'ppwppw';
/* try to connect */
$connection = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
ini_set('memory_limit', '256M');
function Message_Parse($id)
{
global $connection;
if (is_resource($connection))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
$structure = imap_fetchstructure($connection, $id, FT_UID);
if (is_array($structure) && array_key_exists('parts', $structure))
{
foreach ($structure->parts as $key => $part)
{
if (($part->type >= 2) || (($part->ifdisposition == 1) && ($part->disposition == 'ATTACHMENT')))
{
$filename = null;
if ($part->ifparameters == 1)
{
$total_parameters = count($part->parameters);
for ($i = 0; $i < $total_parameters; $i++)
{
if (($part->parameters[$i]->attribute == 'NAME') || ($part->parameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->parameters[$i]->value;
break;
}
}
if (is_null($filename))
{
if ($part->ifdparameters == 1)
{
$total_dparameters = count($part->dparameters);
for ($i = 0; $i < $total_dparameters; $i++)
{
if (($part->dparameters[$i]->attribute == 'NAME') || ($part->dparameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->dparameters[$i]->value;
break;
}
}
}
}
}
$result['attachments'][] = array
(
'filename' => $filename,
'content' => str_replace(array("\r", "\n"), '', trim(imap_fetchbody($connection, $id, ($key + 1), FT_UID))),
);
}
else
{
if ($part->subtype == 'PLAIN')
{
$result['text'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else if ($part->subtype == 'HTML')
{
$result['html'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else
{
foreach ($part->parts as $alternative_key => $alternative_part)
{
if ($alternative_part->subtype == 'PLAIN')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['text'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
else if ($alternative_part->subtype == 'HTML')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['html'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
}
}
}
}
}
else
{
$result['text'] = imap_body($connection, $id, FT_UID);
}
$result['text'] = imap_qprint($result['text']);
$result['html'] = imap_qprint(imap_8bit($result['html']));
return $result;
}
return false;
}
$emails = imap_search($connection,'ALL');
rsort($emails);
foreach($emails as $email_number) {
$result = Message_Parse($email_number);
$data = $result['attachments'];
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$attachment = Swift_Attachment::newInstance($data, 'recorded.mp3', 'audio/mp3');
$message = Swift_Message::newInstance('new messaeg')
->setFrom(array('aaa#bbb.com' => 'name'))
->setTo(array('aaa#ccc.com'))
->setBody($result['text'], 'Here is the message itself')
->attach($attachment);
$result1 = $mailer->send($message);
?>
What is $data after $data = $result['attachments'];? Think it is an attachment container object of some sort. You might need to dig in a little more to get the right property (the attachment) to then reattach it. See: http://dev.kayako.com/browse/SWIFT-2341
This doesn't look right:
$data = $result['attachments'];
...
$attachment = Swift_Attachment::newInstance($data, 'recorded.mp3', 'audio/mp3');
When you create an attachment with this method, I think $data is supposed to be a string that contains the contents of the attachment. But $result['attachments'] is an array of all the attachments in the original message. It seems like you should be looping through these attachments, creating a separate Swift_Attachment for each of them. You also should save the filename and content type from the original message, not hard-code them to recorded.mp3 and audio/mp3 (unless the application ensures that this is all there will be).
As for them being encoded -- MP3's aren't plain text, so what do you expect?

Bad message number error

I am using a script to forward email addresses and getting bad message number error. the message number is parsed as an argument for the function and i am not sure how to get the message number and insert it as the argument. Please help. I am new to php. The error points out $structure = imap_fetchstructure($connection, $id, FT_UID); and $result['text'] = imap_body($connection, $id, FT_UID); parts. Please help me.
<?php
require_once '../swift/lib/swift_required.php';
$hostname = '{imap.xyz.com:993/imap/ssl}INBOX';
$username = 'email';
$password = 'password';
/* try to connect */
$connection = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
ini_set('memory_limit', '256M');
function Message_Parse($id)
{
global $connection;
if (is_resource($connection))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
$structure = imap_fetchstructure($connection, $id, FT_UID);
//print_r($structure);
//array_key_exists — Checks if the given key or index exists in the array
if (is_array($structure) && array_key_exists('parts', $structure))
{
foreach ($structure->parts as $key => $part)
{
if (($part->type >= 2) || (($part->ifdisposition == 1) && ($part->disposition == 'ATTACHMENT')))
{
$filename = null;
if ($part->ifparameters == 1)
{
$total_parameters = count($part->parameters);
for ($i = 0; $i < $total_parameters; $i++)
{
if (($part->parameters[$i]->attribute == 'NAME') || ($part->parameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->parameters[$i]->value;
break;
}
}
if (is_null($filename))
{
if ($part->ifdparameters == 1)
{
$total_dparameters = count($part->dparameters);
for ($i = 0; $i < $total_dparameters; $i++)
{
if (($part->dparameters[$i]->attribute == 'NAME') || ($part->dparameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->dparameters[$i]->value;
break;
}
}
}
}
}
$result['attachments'][] = array
(
'filename' => $filename,
'content' => str_replace(array("\r", "\n"), '', trim(imap_fetchbody($connection, $id, ($key + 1), FT_UID))),
);
}
else
{
if ($part->subtype == 'PLAIN')
{
$result['text'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else if ($part->subtype == 'HTML')
{
$result['html'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else
{
foreach ($part->parts as $alternative_key => $alternative_part)
{
if ($alternative_part->subtype == 'PLAIN')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['text'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
else if ($alternative_part->subtype == 'HTML')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['html'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
}
}
}
}
}
else
{
$result['text'] = imap_body($connection, $id, FT_UID);
}
$result['text'] = imap_qprint($result['text']);
$result['html'] = imap_qprint(imap_8bit($result['html']));
return $result;
}
return false;
}
$emails = imap_search($connection,'ALL');
// rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
echo $email_number;
$result = Message_Parse($email_number);
//$data = $result['attachments'];
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
//$attachment = Swift_Attachment::newInstance($result['attachments'], $filename, 'audio/mp3');
$message = Swift_Message::newInstance('test message1 ')
->setFrom(array('from address' => 'name'))
->setTo(array('to address.com'))
->setBody($result['text']);
// ->attach($attachment);
$result1 = $mailer->send($message);
}
?>
The FT_UID flag means that you are using message uid, rather than message sequence id. In order to get the uid for a given message, you have to use the msg_uid() function.
Since you are beginner, I hardly think this was your question, so here is complete example how to get the headers and the content of a given message:
<?php
$emailAddress = 'postmaster#example.com';
$password = 'someSecretPassword';
$server = 'localhost';
$folder = 'Inbox';
$dsn = sprintf('{%s}%s', $server, $folder);
$mbox = imap_open($dsn, $emailAddress, $password);
if (!$mbox) {
die ('Unable to connect');
}
$status = imap_status($mbox, $dsn, SA_ALL);
$msgs = imap_sort($mbox, SORTDATE, 1, SE_UID);
foreach ($msgs as $msguid) {
$msgno = imap_msgno($mbox, $msguid);
$headers = imap_headerinfo($mbox, $msgno);
$structure = imap_fetchstructure($mbox, $msguid, FT_UID);
var_dump($headers);
var_dump($structure);
}
I was getting the same error when inside the loop, after processing the email, I was moving the message to a different folder.
After I comment out the imap_move the error went away.

Categories