php imap get from email address - php

How do I retrieve the email address from an email with imap_open?
If the sender name is known I get the sender name instead of the email address if I use the 'from' parameter.
Code: http://gist.github.com/514207

$header = imap_headerinfo($imap_conn, $msgnum);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;

I battled with this as well but the following works:
// Get email address
$header = imap_header($imap, $result); // get first mails header
echo '<p>Name: ' . $header->fromaddress . '<p>';
echo '<p>Email: ' . $header->senderaddress . '<p>';
I had used imap_fetch_overview() but the imap_header() gave me all the information I needed.

Worst case, you can parse the headers yourself with something like:
<?php
$headers=imap_fetchheader($imap, $msgid);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $headers, $matches);
?>
$matches will contain 3 arrays:
$matches[0] are the full-lines (such as "To: user#user.com\r\n")
$matches[1] will be the header (such as "To")
$matches[2] will be the value (user#user.com)
Got this from: http://www.php.net/manual/en/function.imap-fetchheader.php#82339

Had same issue as you....had to piece it together, don't know why it's such gonzoware.
Untested example here:
$mbox = imap_open(....)
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$header = imap_headerinfo ( $mbox, $msg);
echo '<p>Name / Email Address: ' . $header->from[0]->personal ." ".
$header->from[0]->mailbox ."#". $header->from[0]->host. '<p></br>';
}
imap_close($mbox);

imap_fetch_overview could be what you're looking for: http://www.php.net/manual/en/function.imap-fetch-overview.php
An example of use can be found here: http://davidwalsh.name/gmail-php-imap, specifically
echo $overview[0]->from;
This function is simple, but has limitations. A more exhaustive version is in imap_headerinfo ( http://www.php.net/manual/en/function.imap-headerinfo.php ) which can return detailed arrays of all header data.

Had trouble until I spotted that the $header is an array of stdClass Objects. The following 2 lines worked:
$header=imap_fetch_overview($imap,$countClients,FT_UID);
$strAddress_Sender=$header[0]->from;

Full working code with an online example
Extract email addresses list from inbox using PHP and IMAP
inbox-using-php-and-imap
I think all you need is just to copy the script.
I am publishing two core functions of the code here as well (thanks to Eineki's comment)
function getAddressText(&$emailList, &$nameList, $addressObject) {
$emailList = '';
$nameList = '';
foreach ($addressObject as $object) {
$emailList .= ';';
if (isset($object->personal)) {
$emailList .= $object->personal;
}
$nameList .= ';';
if (isset($object->mailbox) && isset($object->host)) {
$nameList .= $object->mailbox . "#" . $object->host;
}
}
$emailList = ltrim($emailList, ';');
$nameList = ltrim($nameList, ';');
}
function processMessage($mbox, $messageNumber) {
echo $messageNumber;
// get imap_fetch header and put single lines into array
$header = imap_rfc822_parse_headers(imap_fetchheader($mbox, $messageNumber));
$fromEmailList = '';
$fromNameList = '';
if (isset($header->from)) {
getAddressText($fromEmailList, $fromNameList, $header->from);
}
$toEmailList = '';
$toNameList = '';
if (isset($header->to)) {
getAddressText($toEmailList, $toNameList, $header->to);
}
$body = imap_fetchbody($mbox, $messageNumber, 1);
$bodyEmailList = implode(';', extractEmail($body));
print_r(
',' . $fromEmailList . ',' . $fromNameList
. ',' . $toEmailList . ',' . $toNameList
. ',' . $bodyEmailList . "\n"
);
}

Related

imap_search() with for() will not search for sender

The loop ($zeile[$i]) will not be executed, when it is in the imap_search() function.
The syntax ($inbox, 'FROM " ' . $zeile[$i] . ' " ') is like a lot of examples I have found.
Outside of this codeblock it works well.
But inside even the line on the bottom (echo "#" .$zeile[$i]."<br>";) will not show anything.
With a single var ($test = "domain.de";) it works though.
$test = "domain.de";
$zeile = file("blacklist.txt");
for ($i=0;$i < count($zeile); $i++) {
$emails = imap_search($inbox, 'FROM " ' . $zeile[$i] . ' " ');
if ($emails) {
foreach ($emails as $email_number) {
imap_setflag_full($inbox, $uid, "\\Seen", ST_UID);
echo "#" .$zeile[$i]."<br>";
}
} // if emils
} //Dateischleife
imap_close($inbox, CL_EXPUNGE);
okay, I found the problem.
The first email address from the text file determines the number of $ mails and thus the number of loops of if ($ mails). After that, there is no turning back to the line above.

how to make if decision in swiftmailer to check if field is empty then do not send `td` to mail

I'm trying to send email(s) after submitting a form, I want to achieve:
1) If field is empty then no need to send table row to mail. Just like the field age below is optional, user might add his/her age or might not, so how to do it in switmail $message->addPart('Message','text/html') function.
I tried but failed saying:
Parse error: syntax error, unexpected 'if' (T_IF) in...
The issue is only with if.. without if statement everything works fine.
$content = '<table>
...
<tr><td>' . $_POST["firstname"] . '<td></tr>
' . if(!empty($_POST["age"])) {
. '<tr><td>' . $_POST["age"] . '</td></tr>' .
}
...
<table>';
$message->addPart($content, 'text/html');
Do it outside of the $content variable.
$age = (!empty($_POST["age"])) ? '<tr><td>' . $_POST["age"] . '</td></tr>' : '';
$content = '<table>
...
<tr><td>' . $_POST["firstname"] . '<td></tr>'
. $age . '
...
<table>';

adding a line feed when building a string php

i have been looking all over and i cant find the answer. i am sure this is easy
i am sending an email, and in the body are names of clients
the code looks for clients that fit the search conditions and as each one is found it goes into a loop
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . ???
}
the result should be
Client1
Client2
Client3
but what i keep getting is:
Client1Client2Client3
I have tried
$clients = $clients . $first_name . lf;
$clients = $clients . $first_name . cr;
$clients = $clients . $first_name . '\n';
but always the same result
TIA
If your output will be the command line, file, etc. Use PHP_EOL. If it will be a web browser use <br>:
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . PHP_EOL;
}
while($row = mysql_fetch_array($result)) {
$clients = $clients . $first_name . "<br/>";
}
For text e-mails, the simplest case would be:
$clients = $clients . $first_name . "\n";
Note that you need to enclose \n in double (") instead of single (`) quotes, so that it gets treated as a new line character.
If you are sending HTML e-mails, then you'll need the appropriate HTML tag, i.e. <br>
You can use "\n" or PHP_EOL (single quoted strings like '\n' are not interpolated)
$clients = $clients . $first_name . PHP_EOL;
If you're outputting this to the browser, newline characters are not displayed in html, so you can do something like this:
print nl2br($clients);
Or this:
header('Content-type: text/plain');
print $clients;`
Or this:
printf('<pre>%s</pre>', $clients);

URL parsing and sessions in Reservation system

I am creating a flight/hotel reservation system like farecompare.com Farecompare parse values to other sites and create sessions other sites too. Anyone tell me how they create sesssions in it. I can parse url but i am not able to create sessions.
public function flight($depart, $return, $from, $to, $type, $class,
$adults, $seniors, $children) {
$dep = explode("/", $depart);
$ret = explode("/", $return);
if ($type == 'RoundTrip') {
$expurl = 'http://www.expedia.co.in/Flights-Search?trip=' .
strtolower($type) . '&leg1=from%3A' . $from .
'%29%2Cto%3A' . $to .
'%29%2Cdeparture%3A' . $dep[1] .
'/'.$dep[0].'/'.$dep[2].
'TANYT&leg2=from%3A' . $to .
'%29%2Cto%3A' . $from .
'%29%2Cdeparture%3A' .
$ret[1].'/'.$ret[0].'/'.$ret[2] .
'TANYT&passengers=children%3A' . $children .
'%2Cadults%3A' . $adults .
'%2Cseniors%3A' . $seniors .
'%2Cinfantinlap%3AY&options=cabinclass%3Aeconomy'.
'%2Cnopenalty%3AN%2Csortby%3Aprice&mode=search';
echo 'Expedia';
} else {
$type = 'oneway';
$expurl = 'http://www.expedia.co.in/Flights-Search?trip='.
strtolower($type) . '&leg1=from%3A' . $from .
'%29%2Cto%3A' . $to . '%29%2Cdeparture%3A' .
$dep[1].'/'.$dep[0].'/'.$dep[2] .
'TANYT&passengers=children%3A' . $children .
'%2Cadults%3A' . $adults .
'%2Cseniors%3A' . $seniors .
'%2Cinfantinlap%3AY&options=cabinclass%3Aeconomy'.
'%2Cnopenalty%3AN%2Csortby%3Aprice&mode=search';
echo 'Expedia';
}
}
I worked on Expedia by parsing url to get data but there are other sites like cheapoait, travelocity etc which uses sessions. How to create sessions?
I would assume they store it in the cookies.
We can not access session data of other domain on our site. Data transfer done using web services SOAP OR REST in form of XML. That can be retrieved on other domain and store in session and cookies and use for calculation in website.

What is the best method to return JS within a PHP function?

so I have this PHP function which returns html/js. But I find the method I am using is wrong and not efficient. Is there a better way?
Here is just a simplified version of the code.
function doSomething() {
$speed = 1000;
$duration = 500;
$start = false; // this is a boolean and doesn't work below (not sure why)
$output = '<div class="container">something</div>' . "\r\n";
$output .= '<script type="text/javascript">' . "\r\n";
$output .= 'jQuery(document).ready(function() {' . "\r\n";
$output .= 'jQuery(".container.").cycle({' . "\r\n";
$output .= 'speed : ' . $speed . ',' . "\r\n";
$output .= 'duration : ' . $duration . ',' . "\r\n";
$output .= 'start : ' . $start . "\r\n"; // this doesn't work I think is because of it becoming a string instead of a boolean here.
$output .= '})' . "\r\n";
$output .= '})' . "\r\n";
$output .= '</script> . "\r\n";
return $output;
}
So as you can see above a bunch of output and bunch of linebreaks and basically very hard to maintain and debug. In addition, the START variable isn't working per the comment.
There has to be a better way. I thought about heredocs? But not sure...
Thanks for looking.
I would use something like the following:
function doSomething() {
$speed = 1000;
$duration = 500;
$start = (int)false; // this is a boolean and doesn't work below (not sure why)
$output = <<<END
<div class="container">something</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".container").cycle({
speed : $speed ,
duration : $duration,
start : $start
})
})
</script>
END;
return $output;
}
echo doSomething();
easy to maintain
You could do something like this:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$output = '<div class="container">something</div>' . "\r\n";
$output .= '<script type="text/javascript">' . "\r\n";
$output .= 'jQuery(document).ready(function() {' . "\r\n";
$output .= 'jQuery(".container.").cycle(' . "\r\n";
$output .= json_encode( $cycleArguments );
$output .= ')' . "\r\n";
$output .= '})' . "\r\n";
$output .= '</script>' . "\r\n";
return $output;
}
And with a combination of json_encode() and heredoc syntax:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$jsonCycleArguments = json_encode( $cycleArguments );
$output = <<<OUTPUT
<div class="container">something</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".container.").cycle( $jsonCycleArguments );
});
</script>
OUTPUT;
return $output;
}
Another option, still, could be:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$output = array(
'<div class="container">something</div>',
'<script type="text/javascript">',
'jQuery(document).ready(function() {',
' jQuery(".container.").cycle(' . json_encode( $cycleArguments ) . ');',
'});',
'</script>'
);
return implode( "\r\n", $output );
}
etc...
You can write your code in separate HTML file make AJAX call to that file from php and get code of HTML page in AJAX response use as you want.
Here are a couple of options:
1) at the top of your page (or if you have modularized all JS, and none of it will fire until the bottom of the page, before you call an initialize on anything), have php dump a JSON-encoded multidimensional array, containing all of the data you need on that page, into a single var.
Your JS (stored in static files) will have that var passed into one of the init functions, and will operate on that data.
2) call a php script from the html page src="script.php" from there, store the JS as a separate include, either as a HEREDOC or with template values.
Get your values, plug them into the template and echo the string back.
For this to work, you have to mess with MIME types for this to work properly.
3) rewrite your apache installation to rewrite names, write a routing script which will handle the value grabbing and templates, and return a mime type based on the file-extension which was requested.
This is way-overkill for most sites, but is useful for large sites which want all JS to be external, want JS files to contain dynamic data, AND want all script tags to have regular looking src tags.
An alternative would be to set php to treat ".js" files like php files (but then you need to figure out the type in the script, to set the MIME type).

Categories