imap_open function in PHP sometimes see blank message body - php

I am using imap_open function in PHP to download emails and insert them into a mysql database
Here is my code to get the headers and body message etc:
$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
$header=imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox,$email_number);
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress=$header->to[0]->mailbox."#".$header->to[0]->host;
$replyto=$header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$datetime=date("Y-m-d H:i:s",$header->udate);
$subject=$header->subject;
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));
if($message == '')
{
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1));
}
}
}
but it doesnt seem to get the body of all emails. For example, when it receives Read Receipts the body is just blank and the same with some other emails people send.
sometimes, the email body looks like:
PGh0bWw+DQo8aGVhZD4NCjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIgY29udGVudD0i dGV4dC9odG1sOyBjaGFyc2V0PXV0Zi04Ij4NCjwvaGVhZD4NCjxib2R5IHN0eWxlPSJ3b3JkLXdy YXA6IGJyZWFrLXdvcmQ7IC13ZWJraXQtbmJzcC1tb2RlOiBzcGFjZTsgLXdlYmtpdC1saW5lLWJy ZWFrOiBhZnRlci13aGl0ZS1zcGFjZTsgY29sb3I6IHJnYigwLCAwLCAwKTsgZm9udC1zaXplOiAx NHB4OyBmb250LWZhbWlseTogQ2FsaWJyaSwgc2Fucy1zZXJpZjsiPg0KPGRpdj4NCjxkaXY+DQo8 ZGl2PnJlcGx5PC9kaXY+DQo8ZGl2Pg0KPHAgc3R5bGU9ImZvbnQtZmFtaWx5OiBDYWxpYnJpOyBt YXJnaW46IDBweCAwcHggMTJweDsiPjxiPktpbmQgUmVnYXJkcyw8YnI+DQo8YnI+DQpDaGFybGll IEZvcmQgfCZuYnNwOzwvYj48c3BhbiBzdHlsZT0iY29sb3I6IHJnYigyNTIsIDc5LCA4KTsiPjxi PlRlY2huaWNhbCBNYW5hZ2VyJm5ic3A7PC9iPjwvc3Bhbj48Yj58Jm5ic3A7SW50ZWdyYSBEaWdp dGFsPC9iPjxmb250IGNvbG9yPSIjNTk1OTU ... continued
How can i convert the whole message body to be plain text

Here's what I use, in general. $email refers to one of the objects from the return of eg imap_fetch_overview:
$structure = imap_fetchstructure($email->msgno);
$body = imap_fetchbody($email->msgno, '1');
if (3 === $structure->encoding) {
$body = imap_base64($body);
} else if (4 === $structure->encoding) {
$body = imap_qprint($body);
}
Note there are 6 possible encodings (ranging from 0 to 5), and I'm only handling 2 of them (3 and 4) -- you might want to handle all of them.
Also note I'm also getting only the 1st part (in imap_fetchbody) -- you might want to loop over the pieces to get them as needed.
Update
One other thing I noticed about your code. You're doing imap_fetchbody($inbox,$email_number,1.1). That third argument should be a string, not a number. Do this instead:
imap_fetchbody($inbox, $email_number, '1.1')

The code given handles only simple text messages having at most one sub-part and no encoding. This is basically the simplest kind of email there is. The world used to be that simple, sadly no more!
To handle more email, your code must be expanded to handle:
Multi-parts
Encodings
Multi-part is the concept that a single email message (a bunch of data) can be divided into multiple, logically-separate pieces. In the simplest case, there is only one part: the text of the message. In the next simplest case, there is message text with a single attachment. The next simplest case is message text plus multiple attachments. Then it starts to get hard, when the text of the message refers inline or embeds the attachments (think of an HTML message with an image -- that image could be an attachment that's linked with "local" CSS or embedded as eg base64 data url).
Encoding is the idea that email needs to accommodate the lowest common denominator of SMTP servers on the Internet. From 1971 to the early 1990s, most email messages were plain text using 7-bit US ASCII character set -- and SMTP mailers in the middle relied on this 7-bit framework. As the need for character sets became more apparent, simultaneously with the need to send binary data (eg images), 8-bit SMTP mailers cropped up as did various methods to shoe-horn 8-bit clean data into 7-bits. These include quoted-printable and base64. While 7-bit is virtually dead, we still have all the hoops of this history to jump through.
Rather than re-invent the wheel, there is a good piece of code on PHP.net that handles multi-part encoded messages. See the comment by david at hundsness dot com. You would use that code like this:
$mailbox = imap_open($service, $username, $password) or die('Cannot open mailbox');
// for all messages
$emails = imap_fetch_overview($mailbox, '1:1'/* . imap_check($mbox)->Nmsgs*/);
foreach ($emails as $email) {
// get the info
getmsg($mailbox, $email->msgno);
// now you have info from this message in these global vars:
// $charset,$htmlmsg,$plainmsg,$attachments
echo $plainmsg; // for example
}
imap_close($mailbox);
(Side note: his code has three parse errors, where he does ". =" to mean ".=". Fix those and you're good to go.)
Also, if you're looking for a good blog on doing this "from the ground up", check out this: http://www.electrictoolbox.com/php-imap-message-parts/

Related

Sending encrypted mail from php with non-ASCII Content-type

I am trying the below code to send encrypted mail where the cleartext is text/html and charset is utf-8.
For what it's worth, I cannot manage to get the mail displayed correctly (in MS Outlook).
As you may notice, I (meanwhile) try to have the relevant Content-Type: header both prepended to the data file to be encrypted and present in the headers parameter of the call to openssl_pkcs7_encrypt (and tried various other combinations as well).
While the desired content-type applies to the message when it is sent unencrypted, it simply does not work with encrypted messages. The result is always as if the "inner" Content-Type had been text/plain;charset=ascii.
I experimented with prepending the header to the data file before encryption only because I think I found some suggestion similar here on SE for a similar situation. But apparently this only makes the header line appear as part of the decrypted message (in other words, the file submitted to openssl_pkcs7_encrypt should really only be the "pure" content (as I had orginally suspected).
But having it in the headers parameter does not help, either: In the headers present in the enncryped file, there is a header added with the correct "outer" S/MIME content type, which overrides my "inner" content type given.
Question: Where and how in the combination of openssl_pkcs7_encrypt() and mail() should I specify the "inner" Content-Type of my encrypted message?
$hdr_to = implode(',',$empfaenger);
$hdr_subject = '=?UTF-8?q?' . quoted_printable_encode($subject) . '?=';
$other_headers = array(
"From" => $hdr_from,
"Content-Type" => "text/html; charset=utf-8",
"X-Mailer" => "PHP/".phpversion()
);
$mailbody = wordwrap($_REQUEST['message']);
//write msg to disk
$msg_fn = tempnam("/tmp","MSG");
$enc_fn = tempnam("/tmp","ENC");
$fp = fopen($msg_fn, "w");
fwrite($fp, 'Content-Type: ' . $other_headers['Content-Type'] . CRLF . CRLF);
fwrite($fp, $mailbody);
fclose($fp);
// Encrypt message
$enc_ok = openssl_pkcs7_encrypt($msg_fn,$enc_fn,$pubkeys,$other_headers,PKCS7_TEXT,1);
//$enc_ok = false; // for debugging: simulate encryption failure
if (!$enc_ok) {
// Will try to send unencrypted instead
} else {
// Seperate headers and body for mail()
$data = str_replace("\n",CRLF,file_get_contents($enc_fn));
$parts = explode(CRLF.CRLF, $data, 2);
$mailbody = $parts[1];
$other_headers = $parts[0];
}
// Send mail
$mail_ok = mail($hdr_to, $hdr_subject, $mailbody, $other_headers);
The problem was the PKCS7_TEXT flag given as parameter to the encryption function.
My intended media type was text/html; charset=utf-8, i.e.,
of type text
of subtype html
with parameter charset=utf-8
and superficially, the type matches what the name PKCS7_TEXT suggests. However, this flag is described as:
Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
To be precise, it seems that said header and a blank line (to separate it from the message body) are prepended, which turns any previously existing header lines (Content-Type: or other) into part of the body.
So the simple solution is to not use the PKCS7_TEXT flag (unless your message is really plain ASCII² text).
² It may also be okay for latin-1 text, but I won't count on it. After all the description quoted above suggests that an error will occur; then again, UTF-8 text gets decrypted successfully (i.e., without an explicit error), but exhibits the usual codepage related display artefacts .

E-mail stored usernames and passwords via automated PHP script

I have more than 200 usernames, passwords, and e-mails within an excel sheet as well as a MySQL database. I would like to create a PHP automated script that appends the username and password to a strip of general text and sends it to the e-mail address in the same row.
Is this possible via PHP? I'm brand new to this and was hoping someone could point me in the right direction.
Any tips would be most appreciated!
You retrieve the data form the database and then send emails using PHP's mail function.
From the PHP Manual:
Using mail() to send a simple email:
<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('caffeinated#example.com', 'My Subject', $message);
?>

parsing email attachments in php

I have a .forward.postix that is piping incoming emails to a shell account, and consequently to a PHP script that parses the emails - awesome.
As of now, and based on everything I've seen online, I'm using the explode('From: ', $email); approach to split everything down into the vars I need for my database.
Enter attachments! Using the same approach, I'm doing this to pull out a jpg attachment - but it appears not every email client formats the raw source the same way and it's causing some headaches!
$contentType1 = explode('Content-type: image/jpg;', $email); //start ContentType
$contentType2 = explode("--Boundary_", $contentType1[1]); //end ContentType
$jpg1 = explode("\n\n", $contentType2[0]); //double return starts base64 blob
$jpg2 = explode("\n\n", $jpg1[1]); //double return marks end of base64 blob
$image = base64_decode($jpg2[0]); //decode base64 blob into jpg raw
Here's my issue:
Not all mail clients - like GMail for example - list an attachment as 'Content-type: image/jpg'. GMail puts in 'Content-Type: IMAGE/JPEG' and sometimes sends it as 'Content-Type: image/jpeg'! Which don't match my explode...
My Question: Does someone know a better way of finding the bounds of a base64 blob? or maybe a case-insensitive way of exploding the 'Content-Type:' so I can then try against image/jpg or image-jpeg to see what matches?
You can try to split your string using preg_split(). Maybe something like this
$pattern = '#content-type: image/jpe?g#i';
$split_array = preg_split($pattern, $email);

CodeIgniter SMTP email message - characters replaced with equal signs

I'm using the CodeIgniter email library to send emails using our Exchange server. The problem I get is that the content of the email gets messed up.
There are some words that get replaced with equal signs "=", I tried 2 different Exchange servers (they are in different locations and have no relation what so ever) and I still get the same issue. If I use any other server as an SMTP server to send emails everything works fine and the content stays intact and unchanged.
Content before sending:
Dear Customer
Please find attached a comprehensive explanation of how to get our brochure of Angola. This has been sent to you at the request of Alex.
The information has been taken from www.example.co.uk "Company name" is one of the leading tile and marble companies in the UK.
Content after sending it through the Microsoft Exchange:
Dear Customer
Please find attached a comprehensive explanation of how to get our brochure of A=gola. This has been sent to you at the request of Alex.
The information has been taken from www.example.co.uk "Company name" is one of the leadi=g tile and marble companies in the UK.
As you can see for some reason some of the "n" characters were replaced with equal signs "=" (Example: Angola > A=gola)
My email configuration:
$this->load->library('email');
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
// SMTP
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'exchange.example.com'; //ssl://
$config['smtp_user'] = 'email#example.com';
$config['smtp_pass'] = 'password';
$config['smtp_port'] = 25;
$this->email->set_newline( "\r\n" );
$this->email->initialize( $config );
$this->email->clear();
......
$this->email->from( $frome, $fromn );
$this->email->to( $email );
$this->email->subject( $subject );
$this->email->message( $send_message );
$this->email->send();
Does anyone know why is the Microsoft exchange behaving this way? or is there some sort of setting I should use?
That's odd, specially since not all the ns are transliterated and not at a specific position.
Try calling $this->email->set_crlf( "\r\n" ); as well. Look up the message details in Exchange and inspect the Content-Type and Charset / Encoding - post the raw thing here so we can inspect it.
I found this in Microsoft Knowledgebase:
Microsoft Exchange uses an enhanced character set. The default MIME
character set for Microsoft Exchange is ISO 8859-1. Some gateways do
not support the way this character set issues a soft return for line
feeds. When this occurs, each line is terminated with an equal sign
showing the line break where the gateway's line-length support ends.
I solved this (kinda) by setting $charlim = '998' in the _prep_quoted_printable function.
When I set $crlf = "\r\n" the resulting email was completely garbled for some reason. But I noticed that the = signs were appearing at regular intervals which was caused by the line length being limited to 76 characters. So increasing the max characters per line (998 is the RFC2822 limit) solves the problem, as long as you don't have really long lines.

workaround for the 990 character limitation for email mailservers

Wanted to know if there are any functions/classes/etc.. to help with the 990 character limitation for email as my HTML is being effected due to this.
The Problem: (Source)
Note that mailservers have a
990-character limit on each line
contained within an email message. If
an email message is sent that contains
lines longer than 990-characters,
those lines will be subdivided by
additional line ending characters,
which can cause corruption in the
email message, particularly for HTML
content. To prevent this from
occurring, add your own line-ending
characters at appropriate locations
within the email message to ensure
that no lines are longer than 990
characters.
Anyone else seem to have this problem? and how did you fix this?
Sounds like I need to find a good place to split my HTML and manually add a line break, ugh...
UPDATE:
It's tablature data with many rows. So do I need to add a \n or <br /> somewhere?
UPDATE #2: Adding MIME Type Code
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n"; // added this, but still no results
$headers .= "From: from#email.com\r\n";
Here is how I'm calling the function(s):
How I originally called:
return $html;
What I tried:
return imap_8bit($html); // not working, nothing is captured in the error log
AND
return imap_binary($html); // not working, nothing is captured in the error log
UPDATE #3 (Adding Mail Function)
try {
mail(
'to#email.com',
'Subject of Email',
$html,
$headers
);
} catch (Exception $e) {
echo ("ERROR: Email NOT sent, Exception: ".$e->getMessage());
}
Example HTML (This is the message of the HTML email) (This is also in a class that is part of a XMLRPC service)
private function getHTML() {
$html = '<html><head><title>Title</title></head><body>';
$html .= '<table>';
$html .= '<tr><td>many many rows like this</td></tr>';
$html .= '<tr><td>many many rows like this</td></tr>';
$html .= '<tr><td>many many rows like this</td></tr>';
$html .= '<tr><td>many many rows like this</td></tr>';
$html .= '<tr><td>many many rows like this</td></tr>';
$html .= '</table>';
$html .= '</body>';
$html .= '</html>';
return $html;
//return imap_8bit($html); // not working, nothing is captured in the error log
//return imap_binary($html); // not working, nothing is captured in the error log
// Both of these return the XMLRPC Fault Exception: 651 Failed to parse response
}
Fault Exception: 651 Failed to parse response basically doesn't like the format or how the data is returned.
You can put your content through the wordwrap() function so that you don't manually have to insert newlines.
Have you considered using one of the many mail libraries available? PHPMailer, PEAR Mail, SwiftMailer, etc...?
Order servers have an even lower limit: 76 chars per line + \r\n.
You have to make use of the imap_8bit() and imap_binary() functions in order to convert your data to a base64 or quoted-printable encoding.
You can also use an existing library, like SwiftMailer.
Actually, this is not a "mail server" problem. The SMTP line limit dictates the number of characters allowed on each line during transmission. The SMTP RFC allows for up to 1000 characters per line, and default postfix installed cap at 998 characters. You should contact your hosting provider on increasing your SMTP line limit if you feel it's necessary to exceed the RFC.

Categories