IMAP qprint is not decoding danish charecter? - php

I have completed PHP IMAP code. All the mail result is coming fine. But in the mail if contain any danish character then it show wrong. The code I have done for finding message body is below,
$emails = imap_search($inbox,'ALL');
if($emails) {
rsort($emails);
$total_mail=imap_num_msg($inbox);
echo 'Number of email:'.$total_mail;
/* for every email… */
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);
}
}
As a example the message in the mail is, Låt deras önskningar gå i uppfyllelse i år med perfekta klappar från Apple., and it is showing in he above code output as L�t deras �nskningar g� i uppfyllelse i �r med perfekta klappar fr�n Apple..
I don't know the problem. I have follow all the rules. The charset is also UTF-8 like, charset="UTF-8". But sill have the same problem.
Please help me to solve this. Advance thanks for help.

Related

issues with IMAP functions php

I am facing some problem with imap function. Basically What I need to do is to read unseen mails. There will be a url in all the mails, i should fetch that URL and store.
$inbox = imap_open($hostname,$username,$password);
if($inbox)//if **1
{
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) //if **2
{
/* put the newest emails on top */
rsort($emails);
/* for every email... */
$varients=array("1","1.1","1.2","2");
foreach($emails as $email_number) //for loop **1
{
$ids [] = $email_number;
foreach($varients as $cur_varient) //for loop **2
{
echo "\n\nstarting with imap function number ". $cur_varient."\n\n";
$overview = imap_fetch_overview($inbox,$email_number,0);//all varients of like subject, date etc.
$from = addslashes(trim($overview[0]->from));
$inboxed_time = addslashes(trim(strtotime($overview[0]->date)));
$message = (imap_body($inbox,$email_number,$cur_varient));
print addslashes(trim($overview[0]->subject));break;
preg_match_all('#\bhttp?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $message, $match);
$link_matched = $match[0];
$input = 'unsubscribe.php';
$linkexists = false;
foreach($link_matched as $curlink)
{
if(stripos($curlink, $input) !== false)
{
$linkexists = true;
$unsublink = $curlink;
$unsublink = str_replace('href="', '', $unsublink);
$unsublink = str_replace('"', '', $unsublink);
break;
}
}
if(isset($unsublink))
{
$unsublink = addslashes(trim(($unsublink)));
$thread = 1;
$time = date("Y-m-d H:i:s");
$iQry = " INSERT INTO `SPAMS`.url_queue VALUES(";
$iQry .= " 'default','".$unsublink."','".$thread."','";
$iQry .= "".$from."','".$inboxed_time."',UNIX_TIMESTAMP('".$time."'))";
//mysql_query($iQry);
print $iQry;
}
}//closing for loop **2
}//closing for loop **1
} //closing if **2
// Setting flag from un-seen email to seen on emails ID.
if(isset($ids))
{
imap_setflag_full($inbox,implode(",", $ids), "\\Seen \\Flagged"); //IMPORTANT
}
// colse the connection
imap_expunge($inbox);
imap_close($inbox);
}//closing if **1
I have used all different varients of imap to make sure it will read different types of mails. Now issue is, sometime the URL matched is broken. Only half URL will be fetched(I printed the entire message, saw that half URL is coming to next line). The other issue is, sometimes, the body fetched will not be the one which the current mail contains. It fetched some other mail content.
I am puzzled what to do, so putting my entire code, please help.
You will have to use a regex modifiers to match multiline texts too, or you can strip newlines and such from the body of the emails.
preg_match("/{pattern}/mi",'Testing');
//m for multiline matches and i for case-insensitive matches
Your second issue is a bit different than you'd think, emails have multiple bodies, one for simple texts, one for html, some for attachments (and their order is different in apple products).
https://www.electrictoolbox.com/php-imap-message-parts/
You are probably facing the issue of grabbing the wrong one. My recommendation would be to fetch all of the email bodies, like this:
$overview = imap_fetch_overview($this->connection, $email_number, 0);
$structure = imap_fetchstructure($this->connection, $email_number);
$message = "";
//$parts = [1, 1.1, 1.2, 2];
if (!$structure->parts)//simple email
$message .= "Simple: ". imap_fetchbody($this->connection, $email_number, 0). "<br/>";
else {
foreach ($structure->parts as $partNumber=>$part){
if ($partNumber != 0)
$message .= "Part ".$partNumber.": ". imap_fetchbody($this->connection, $email_number, $partNumber)."<br/>";
}
}

cryptic mail body when using imap_fetchbody

I am using following code to exctract among others the mail body of mails.
$imap = imap_open($mailbox,$user,$password);
$mails = imap_search($imap,'UNSEEN');
foreach($mails as $mail)
{
$message = trim(utf8_encode(quoted_printable_decode(imap_fetchbody($imap,$mail,"1"))));
if(strpos($message,"<html") !== false)
{
$mail_body = fopen($dir."mail.html","w");
}
else
{
$mail_body = fopen($dir."mail.txt","w");
}
}
This is working fine and it works with every test I did.
html-mails, plain-text-mails, also if the mails are forwarded.
Now from some other source I get mails, where the message (after using imap_fetchbody) just looks like some crypted string. Like this:
dGVpZW4gaW0gUERGLUZvcm1hdDoNClJla2xhbWF0aW9uc2luZm9ybWF0aW9uOiAyMTMzNjc0MSBS
SV8yMTMzNjc0MS5wZGYNCg0KTWl0IGZyZXVuZGxpY2hlbiBHcsO8w59lbg0KSWhyIG5vYmlsaWEg
VGVhbQ0KX19fDQoNCm5vYmlsaWEtV2Vya2UgSi4gU3RpY2tsaW5nIEdtYkggJiBDby4gS0cgfCBX
YWxkc3RyLiA1My01NyB8IDMzNDE1IFZlcmwNCg0KRGllIEdlc2VsbHNjaGFmdCBpc3QgZWluZSBL
I already tried to use some other arguments for imap_fetchbody like "1.1" or "1.2", but when I do that the message is empty.
Do you have any idea why this effect occurs?
I finally found a solution. The cause seems to be forwarded mails, that were initially sent from an apple device.
Now I use this to extract the message and it works.
$structure = imap_fetchstructure($imap, $mail);
$part = $structure->parts[1];
$message = imap_fetchbody($imap,$mail,1);
if(strpos($message,"<html") !== false)
{
$message = trim(utf8_encode(quoted_printable_decode($message)));
}
else if($part->encoding == 3)
{
$message = imap_base64($message);
}
else if($part->encoding == 2)
{
$message = imap_binary($message);
}
else if($part->encoding == 1)
{
$message = imap_8bit($message);
}
else
{
$message = trim(utf8_encode(quoted_printable_decode(imap_qprint($message))));
}

imap_search() for unseen messages does not returning anything

I am currently trying to get the UNSEEN/UNREAD messages from my server. Currently, I have this:
$openmail = imap_open($dns, $email, $password) or die("Cannot Connect " . imap_last_error());
if ($openmail) {
/* grab emails */
$emails = imap_search($openmail, 'UNSEEN');
if ($emails) {
//For every e-mail.
$tot = imap_num_msg($openmail);
for ($i = $tot; $i > 0; $i--) {
$structure = imap_fetchstructure($openmail, $i);
if (isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($openmail, $i, 2, FT_PEEK);
if ($part->encoding == 3) {
$message = imap_base64($message);
} else if ($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_qprint($message);
}
}
$header = imap_header($openmail, $i);
$from = imap_utf8($header->fromaddress);
$subject = $header->Subject;
$subject = substr($subject, 0, 150);
$date = $header->Date;
}
/* Print out the Unseen messages in here! */
} else {
/* No unseen messages */
echo "No unseen";
}
}
I've tried sending multiply emails to my mailserver, refreshed the page with the above script. But I keep getting the "No unseen".
I've tried to output the $emails but it's empty. It can't find anything.
If I try to just get ALL the messages (no unseen filter), I can see the emails I've sent to the mailbox, although, they're all marked as read.
Your code $message = imap_fetchbody($openmail, $i, 2, FT_PEEK); uses hardcoded part offsets, i.e. it assumes that a message is always multipart/alternative with text/plain and text/html. That's a very wrong assumption.
You have to look at the output of the BODYSTRUCTURE to see what the MIME structure of your mail is.
With that out of the way, be sure that none of your commands use the BODY fetch operation; you have to use BODY.PEEK. I have no idea how this is accessible within the PHP c-client bindings.

PHP Download Attachments using imap_open(), via CLI

I am so close to finishing this, but I'm stuck on downloading attachments.
So far I'm grabbing all my necessary email header information with the following code:
(also, I'm doing this via command line: CentOS 6)
<?php
echo "\n";
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myemail#mydomain.com';
$password = 'myfunpassword';
/* 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 */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1);
$output.= $email_number."\n";
$output.= ($overview[0]->seen ? '[read]' : '[unread]')."\n";
$output.= "date:".$overview[0]->date."\n";
$output.= "to:".$overview[0]->to."\n";
$output.= "from:".$overview[0]->from."\n";
$output.= "size:".$overview[0]->size."\n"; //size in bytes
$output.= "msgno:".$overview[0]->msgno."\n";
$output.= "message_id:".$overview[0]->message_id."\n"; //Message-ID
$output.= "uid:".$overview[0]->uid."\n"; //UID the message has in the mailbox
$output.= "from:".$overview[0]->from."\n";
$output.= "subject:".$overview[0]->subject."\n";
/* output the email body */
$output.= "message:".$message;
/* detect attachments here */
$output.="\n\n";
}
echo $output;
} // eof $emails check
imap_close($inbox);
?>
This works great!
So now, I've got this code to tell me if there are attachments in each email:
<?php
// put this code above where it says "detect attachments here"
// attachments detection
$struct = imap_fetchstructure($inbox,$email_number);
$contentParts = count($struct->parts);
if ($contentParts >= 2) {
for ($i=2;$i<=$contentParts;$i++) {
$att[$i-2] = imap_bodystruct($inbox,$email_number,$i);
}
for ($k=0;$k<sizeof($att);$k++) {
if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") {
if ($att[$k]->parameters[1]->value != "") {
$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
}
} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") {
$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
}
}
if (sizeof($selectBoxDisplay) > 0) {
for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
$output.= "\n--file:". $selectBoxDisplay[$j]."";
}
}
}
// eof attachments detection
?>
And this works too! But now I'm to the point that I need to download the attachments, and most tutorials show me how to do it using from a browser's point of view, rather than the CLI. So I definitely need a little help here.
I'm expecting there's a way to determine where to download files on the server too.

how can I display the contents of an email to a website?

I would like to display the body contents of an email. I have tried IMAP in php but something is VERY wrong. The IMAP isn't picking up the body of my message. It is picking up ONLY the signature in the body. So I am looking for alternative methods of reading email body contents to a webpage.
here is the original document of my email:
http://pastebin.com/WQra335P
the disclaimer/copyright blur is being grabbed by IMAP but nothing else in the body is being displayed. anyone have alternative methods of reading email from gmail or any other site that can display the contents to a webpage?
I have given up on making IMAP read it because no one has been able to figure out the problem...I have spent hours so I give up but here is the code...
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'username#gmail.com';
$password = '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,'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 */
$overview = imap_fetch_overview($inbox, $email_number, 0);
$message = imap_fetchbody($inbox, $email_number, 2);
echo $message;
echo imap_qprint($message);
$message = imap_qprint($message);
echo imap_8bit ($message);
$DateFormatted = str_replace("-0500", "", $overview[0] -> date);
/* output the email header information */
$output .= $overview[0] -> subject ;
$output .= $DateFormatted ;
//$bodyFormatted = preg_replace("/This e-mail(.*)/","",$message);
//$bodyFormatted = preg_replace("/Ce courriel(.*)/","",$bodyFormatted);
/* output the email body */
$output .= $message;
}
echo $output;
}
/* close the connection */
imap_close($inbox);
?>
In Addition to what DmitryK suggested,
Adding the below makes everything work fine without the random "=" signs. The Str_replace is used to remove the "="s generated over the pages.
$message = imap_fetchbody($inbox, $email_number, "1.1");
$message = str_replace("=", "", $message);
I dont know 100% why the "="s are generated randomly but this is most likely due to some encryption issue from the Exchange Server's side as our server is about 10 years old.
You are dealing with the multi-part messages (looking at your pastebin e-mail sample).
As a test try using this line:
$message = imap_fetchbody($inbox, $email_number, "1.1");
Plain text version lives under 1.1
HTML version is 1.2
The signature is in the next part - it is 2. And this is what you retrieve in your code sample.
Do you have access to the raw email content (the stuff with all the headers etc)
If so, try using plancacke email parser
I have used it before with good success.
$emailParser = new PlancakeEmailParser(...raw email content...);
$emailTo = $emailParser->getTo();
$emailSubject = $emailParser->getSubject();
$emailCc = $emailParser->getCc();
$emailDeliveredToHeader = $emailParser->getHeader('Delivered-To');
$emailBody = $emailParser->getPlainBody();
$emailHtml = $emailParser->getHTMLBody();
Gmail has some different IMAP settings, follow the original code more closely:
http://davidwalsh.name/gmail-php-imap

Categories