imap_fetchbody and stripping below line - php

I have a script that checks emails and puts them in a database. This works fine when new emails are composed and sent. However, if I reply to an email the imap_fetchbody does not work and it is empty.
Where am I going wrong here?
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$structure = imap_fetchstructure($inbox,$email_number);
$message = imap_fetchbody($inbox,$email_number,0);
$header = imap_headerinfo($inbox,$email_number);
//print_r($structure);
//make sure emails are read or do nothing
if($overview[0]->seen = 'read'){
//strip everything below line
$param="## In replies all text above this line is added to the ticket ##";
$strip_func = strpos($message, $param);
$message_new = substr($message,0,$strip_func );
/* output the email body */
$output.= '<div class="body">'.$message_new.'<br><br></div>';
If I output the $message instead of the $message_new so before I start stripping the text everything is displayed.

If that line "In replies..." is not present in the message at all, strpos will return boolean false, which when coerced to an integer will be 0.
So when you ask for the substring from 0 to the position, you're asking for the substring from 0 to 0, and $message_new is empty.
Check if that line is present in the mail before you try to take a substring based on it.
$param="## In replies all text above this line is added to the ticket ##";
$strip_func = strpos($message, $param);
$message_new = ($strip_func === false) ? $message : substr($message,0,$strip_func);

Related

PhpMailer, how do I write the variable value correctly for multiple addCC email address?

I have a PhpMailer working code as follow: (short version)
(the variable already defined before hand)
// Sender and recipient settings
$mail->setFrom($pengirim_email, $pengirim_nama);
$mail->addAddress($untuk_email, $untuk_nama);
$mail->addReplyTo($pengirim_email, $pengirim_nama);
Next, I add multiple email address for CC mail:
$mail-->addCC('aaa#gmail.com','Abdul');
$mail-->addCC('bbb#gmail.com','Borat');
It work as expected.
Now since I'm planning that the email address will come from the SQL query, so for the time being I want to know how do I have to fill the SQL 'CarbonCopy' column table with multiple email addresses - by trying to make a "hardcoded" variable value. So I try like this as the replacement for the addCC above:
$tembusan="'aaa#gmail.com','Abdul';'bbb#gmail.com','Borat'"; //not working
$CC = explode(';', $tembusan); //not working
for ($i = 0; $i < count($CC); $i++) {$mail->addCC($CC[$i]);} //not working
But it throw me an error like this :
Error in sending email. Mailer Error: Invalid address: (cc):
'aaa#gmail.com','Abdul'
So I change the $tembusan into like this:
$tembusan="aaa#gmail.com,Abdul;bbb#gmail.com,Borat"; //not working
It gives me almost the same like the error before:
Error in sending email. Mailer Error: Invalid address: (cc):
aaa#gmail.com,Abdul
Next, I try also this kind of code :
$tembusan="'aaa#gmail.com','Abdul';'bbb#gmail.com','Borat'"; //not working
$CC = explode(';', $tembusan); //not working
foreach($CC as $CCemail){$mail->AddCC($CCemail;} //not working
And it also throw the same error:
Error in sending email. Mailer Error: Invalid address: (cc):
'aaa#gmail.com','Abdul'
If I echo the last code like this foreach($CC as $CCemail){echo $CCemail. '<br/>';}, it give me a result like this :
'aaa#gmail.com','Abdul'
'bbb#gmail.com','Borat'
In my real code, I have a valid email address. The email address in the code above is just for an example.
Where did I do wrong ?
PS
btw, if I remove the "name" for the email address:
$tembusan="aaa#gmail.com;bbb#gmail.com"; //working
$CC = explode(';', $tembusan); //working
foreach($CC as $CCemail){$mail->AddCC($CCemail;} //working
it runs as expected (but in the gmail, the CC name is aaa and bbb).
Please do a further explode . try
$tembusan="aaa#gmail.com,Abdul;bbb#gmail.com,Borat";
$CC = explode(';', $tembusan);
for ($i = 0; $i < count($CC); $i++) {
$DD = explode(',', $CC[$i]);
$mail->addCC($DD[0], $DD[1]);
}
Please note that I have removed the ' characters . (you may use str_replace of PHP to eliminate these characters)

Getting Mail body In PHP

What I am doing:
First I am trying to get email and save the reply of user in my database.
For this I am using PHP imap method to get mail from my email address.
Code:
function get_email()
{
//define server, email , password
$server = '{server.example.com:143}INBOX';
$user_name = 'login';
$user_pass = 'password';
$mail = imap_open( $server , $user_name , $user_pass );
$headers = imap_num_msg($mail);//counting the no of msg
for ($i = 1; $i <= $headers ; $i++)
{
$body = imap_fetchbody($mail, $i ,1);
$body = explode(">",$body);
$body = $body['0'];
$body = substr($body, 0, -5);
echo "<pre>";
echo "/-/-/-/-/-/".$body."/-/-/-/-/-/";
echo "</pre>";
}
// close the connection
imap_close($mail);
}
Now:
The Result that i am getting from $body = imap_fetchbody($mail, $i ,$i); is this:
Okay What new in it.
On Thu, Feb 12, 2015 at 4:56 PM, admin wrote:
> My name is admin!
>
>
but only wanted a the msg body that Okay What new in it. . So I explode() the massage and get the first element of array and remove the last line.
Problem:
I could not remove last line the current result of this program Is:
Okay What new in it.
On Thu, Feb 12, 2015 at 4:56 PM, admin
Even I have add "/-/-/-/-/-/" symbol but the symbol are not showing.
Your approach is not ideal, and this answer will not be ideal either. Because frankly what you are trying to accomplish can be quite difficult, because previous messages in a thread on emails will be different depending on client used and you cannot trust the user either (the thread below the 'body' could have been altered by the user etc.)
Using explode by '>' is not ideal, because what if it is part of the message?
exploding by \n> is a no go too because a user might inline responses as #Michael_Berkovski said.
Anyways here is my solution:
$body = preg_replace('#(\n>.*?)+$#','',$body);
This will reduce the following:
This is the body
> And this is a comment within the body
Also just the body
>Previous messages
>here
>> Even indented who cares?
to:
This is the body
> And this is a comment within the body
Also just the body
For trying very hard I come to a solution that ask user to reply with '#' at the end of the massage. As I notice there are different types of replies from different mailing services but all services show reply first.
Code:
$msgno = imap_num_msg($mail);
for ($i = 1; $i <= $msgno ; $i++)
{
$body = imap_fetchbody($mail, $i ,1);
$body = explode("#",$body);
$body = $body['0'];
echo $body;
echo "<br>";
}
From this I got my desire result.

Bad Message number error in imap_fetchbody function

I have a code to search though emails & if particular string is found, stuff will be done. Below is my code:
$date = date( "d-M-Y", strToTime( "-1 days" ));
$email=imap_search($inbox, 'SUBJECT "Undelivered Mail Returned to Sender" SINCE
"'.$date.'"', SE_UID);
if($email){
foreach($email as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1); /* This is Line 18 */
This code gives me following error:
Warning: imap_fetchbody() [function.imap-fetchbody]: Bad message number in
/home/public_html/example.com/check_invalid_email.php on line 18
Now on the above code if I change the subject only like this:
$email=imap_search($inbox, 'SUBJECT "Mail delivery failed" SINCE
"'.$date.'"', SE_UID);
It works like a charm with this. For your information there are emails with both the subjects.
I've not included my whole code, please consider everything is alright as changing one line gives me desired results.
Any help with this? I'm not able to find out the cause of it.
i think you have to use it like this as you are getting the key,value array
foreach($email as $key=>$email_number) {

Foreign Characters in HTML Email

I wrote a script that takes HTML input from a web page and sends it out as an HTML email. For some reason there are foreign characters, usually exclamation points, showing up in the email that arrives in our inboxes that do not exist in the input. I've checked for hidden characters and there are none. The input is not being copied and pasted but directly entered. Here's a before and after example.
Input:
<p>Katherine Kemler, LSU flute professor, will perform at 7:30 p.m. Feb. 1 in Wattenbarger Auditorium. The performance is free and open to the public.</p>
Output: http://img42.com/LKEou
You can see the erroneous characters between Feb. and 1 and after Watt. I don't think it's the email client because it's the same in every client I've checked.
I've read some other questions around here that have led me to try things like using UTF-8 encoding instead of ISO-8859-1, using base64_encode() on the body, setting the content-transfer-encoding to 8bit but none of that has worked. I've read something about needing a line break after 998 characters but these exclamation points aren't showing up in way that suggests that to me. In my example above, one follows only ten characters after another. Here's my script:
<?php
if(!isset($_GET["id"])) return "<span class=\"text-error\">No ID specified.</span>"; //this should never happen
$id = $_GET["id"];
$ok = false;
$students = //redacted
$facstaff = //redacted
$studentsBCC = //redacted
$facstaffBCC = //redacted
$subject = "Tech Times for ".date("m/d");
$headers = "From: \"Tennessee Tech University\" <techtimes#tntech.edu>\r\n".
"Reply-to: no-reply#tntech.edu\r\n".
"MIME-Version: 1.0\r\n".
"Content-Transfer-Encoding: 8bit\r\n".
"Content-type: text/html; charset=UTF-8\r\n".//iso-8859-1\r\n".
"X-Mailer: PHP/".phpversion();
$resource = $modx->getObject("modResource", $id);
if(is_null($resource)) return "<span class=\"text-error\">Failed to get Resource $id</span>"; //this should never happen either
//get the template and insert the content
$body = $modx->getChunk("techtimes", array("copy"=>$resource->getContent(), "headerimg"=>$resource->getTVValue("headerImg")));
//check to see if this is a test run and if so reassign destination email address and empty BCCs
if(isset($_GET["email"])){
$facstaff = $_GET["email"];
$students = $_GET["email"];
$studentsBCC = "";
$facstaffBCC = "";
}
switch($id){
case 50: $ok = mail($facstaff,$subject,$body,$headers."\r\nBcc:".$facstaffBCC); break;
case 51: $ok = mail($students,$subject,$body,$headers."\r\nBcc:".$studentsBCC); break;
default: return "<span class=\"text-error\">Invalid or no ID specified for Tech Times.</span>"; //this, too, should never happen
}
if($ok){
$output = "<span class=\"text-success\">Tech Times for <strong>".(($id == 50) ? "Fac/Staff" : "students")." ($id)</strong> has been sent to <strong>".(($id == 50) ? $facstaff : $students)."</strong></span>.";
}else{ //this could happen if something goes wrong with the mailer
$error = error_get_last();
var_dump($error);
$output = "<span class=\"text-error\">Failed to send Tech Times!</span>";
}
return $output;
?>
I'm using MODx Revolution to format the output. I'm stumped.
Help?
Thanks!

imap_fetchbody - Encoded body error

I am trying to fetch a particular section of an email body using:
$message = imap_fetchbody ($imap_stream,$n,1);
This works fine for emails sent using Outlook, Hotmail, Yahoo etc. But when I try and fetch the body of the an email sent from a Blackberry or Andriod device, the message is encoded and scrambled such as:
xmb250IHN0eWxlPSdjb2xvcjojRjk3MWIxMDNiMTEyYjExOGI0N2I1MWI1
Although the body is encoded, the header is fine. How do I decode the message body of en email sent from an Android or Blackberry device?
Thank you,
Chris.
You should be able to run imap_fetchstructure to get the encoded value. If that value equals 3 you need to decode via imap_base64.
I've used the following before (Can't remember if it was ever tested with sent mobile email before though):
$structure = imap_fetchstructure($stream, $msgno);
$text = imap_fetchbody($stream, $msgno, $partnum);
if($structure->encoding == 3) {
$text = imap_base64($text);
} else if($structure->encoding == 4) {
$text = imap_qprint($text);
}

Categories