Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward an email downloaded by PHP and IMAP?

I'm writing a script to read email and distribute it to different email addresses depending on the TO address. All email comes to one address, but I cannot seem to figure out how to forward an email, or create a new email and include all of the relevant message body.

Right now I'm downloading the email using IMAP and using imap_fetchbody to get the email contents;

$email_body = imap_fetchbody($imapconnex, $msgnumber, 1);

Some email bodies don't display correctly, and others contain short lines with an = symbol at the end, causing the content to not display correctly. Also, I'm seeing random A0 printed in my email bodies randomly.

My plan was to use PHP's mail() function to send the email to where I want it to go and change the From address to the real From address. That would work for my needs, but I cannot seem to figure out how to retrieve the correct body, format it and send it.

Here's my code that I'm using to send the email:

$header = imap_fetch_overview($imapconnex, $search[$i]);
$email_subject = $header[0]->subject;
$email_head = imap_fetchbody($imapconnex, $search[$i], 0); 
$email_body = imap_fetchbody($imapconnex, $search[$i], 1); 
mail("[email protected]", $email_subject, $email_body, $email_head);

The headers seem to be forwarding fine, but the main body of the message is still displaying with = and A0 symbols.

like image 584
Gary Evans Avatar asked Nov 12 '22 21:11

Gary Evans


1 Answers

Marc

Nice answer and provides a simple solution. It can also handle plain text with some minor changes.

$mtype = array('text', 'multipart', 'message', 'application', 'audio', 
               'image', 'video', 'model', 'other');
$mailstructure = imap_fetchstructure($mbox, $msgno, FT_UID); //
$type = $mailstructure->type;
if ($type == 1 && $mailstructure->ifparameters == 1) {
    $parameters = $mailstructure->parameters;
    $attribute = $parameters[0]->attribute;
    $value = $parameters[0]->value;
    echo $attribute . "//" . $value . "<br />";
}
# prepare the mail
$to="";
$subject="";
//   line below (may) not (be) needed
//   $body="\r\nThis is a multipart message in MIME format.\r\n";
$body = imap_body($inbox, $uid, FT_UID);
$headers ="From:" . $from . "\r\n";
$headers .="Date: " . date("r") . "\r\n";
$headers .="MIME-Version: 1.0\r\n";
$headers .="Content-Type: " . $mtype[$mailstructure->type] . '/'
         . strtolower($mailstructure->subtype) . ";\r\n";
if ($type == 1) { // multipart
    $headers .= "\t boundary=\"" . $value . "\""."\r\n";
}
$sendmail = imap_mail($to, $subject, $body, $headers);
like image 118
AnGus King Avatar answered Nov 15 '22 10:11

AnGus King