mos33
September 8, 2014, 3:46pm
1
I have a problem in reading emails from GMAIL, I uses the following script:
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'xxxxxxxxx@gmail.com';
$password = 'xxxxxxx';
$imap_client = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'xxxxxxxxxxxxx@gmail.com', 'xxxxxxxx');
if (!$imap_client) {
echo imap_last_error();
exit;
}
$emails = imap_search($imap_client, 'UNSEEN');
foreach ($emails as $email_id) {
// $body = imap_body($imap_client, $email_id);
// analyze $body
//echo $body;
$text = imap_fetchbody($imap_client, $email_id,'1');
echo base64_decode($text);
}
imap_close($imap_client);
?>
but the output of the email body is broken, it is like that in case of the message in English:
����
Please help
tpunt
September 8, 2014, 9:44pm
2
The question mark in a black diamond represents an unrepresentable character. Have you tried setting the character encoding for the web page to utf-8?
You can do this either with the PHP header function:
header('Content-Type: text/html; charset=utf-8');
or by using the meta tag in HTML:
<meta charset="utf-8" />
Thanks, problem solved.
How can I write the output of the email body to a text file or an image (with keeping the correct encoding)?
tpunt
September 9, 2014, 8:58am
4
To write the output to an image, you simply need to set the page to utf-8 encoding (with PHP’s header function). If your text files aren’t defaulting to utf-8 in format, then you’ll want to include a Byte Order Mark (BOM) to the top of the text file’s content. This can be done by appending \xEF\xBB\xBF
to the start of the text:
file_put_contents($file, "\xEF\xBB\xBF{$text}");