Calling functions through mail
Wanted to know if its possible to invoke functions through mail using PHP.
开发者_如何学编程For eg. Suppose I have an ebay like application and have configured a mail account for the same. So when a user sends a mail saying with message body with the word "iPod" - immediately a function in my application will get invoked which will mail the specifications of iPod back to the user.
Any rough idea how do I go about to achieve this ??
UPDATE : Sending the mail back is not the problem, that can be easily achieved. I am not able to figure out the way to do the former part. How do I know that I received a mail - is what I am stuck at.
The usual solution is to use a tool such as procmail in conjunction with your SMTP server to conditionally filter incoming messages into your script.
For example, this pushes all email under a certain size into the program spamc
.
:0fw
* < 512000
| spamc
as far as i know, theres no out-of-the-box function to do this. what you'll have to do is to write a script that connects to your mail-server and loads all new mails (this is definitely done by someone else before, try to ask google). after that parse the mails, look for keywords like "iPod" ans send a mail back to the user (basicalls using mail, but tjere are a lot of better packages out there (look for "sendmail"), performing better if you send a lot of mails (the php-mail() connects and disconnects to the mail server for every mail sent))
Yes, you can do this. I'm far from an expert, but I've done it successfully, and here's what I understand.
The keywords you're looking for are IMAP and POP. Almost all email providers have POP, and most of them also have IMAP. These are just ways of streaming the messages in your inbox out to a script. IMAP is apparently better.
To use IMAP in PHP
- first confirm your provider supports it
- make sure it's enabled in your account settings
- in
php.ini
, uncomment the imap extension - also uncomment the SSL extension.
Then, you can use this example string to make your connection. This one's for GMail but it's not too much different for other providers:
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'youraccount@gmail.com';
$password = 'yourpassword';
//========== Open mails in inbox as imap datastream
$imapStream = imap_open($hostname,$username,$password)
or die('Cannot connect to gmail:<br />'.imap_last_error());
That's the hardest part, but it's not too bad.
You can then use the imap_search()
function to filter messages from the stream. The PHP imap function set is pretty easy to use but will take you several hours or days to understand everything (more or less).
To fetch the body of a message, for example, you'd use
imap_fetchbody($imapStream,$i,1.1)
on the code above, where $i
is the message number from your imap_search()
results. Then, search your string. If found, fire your function.
To test if you've received a mail, you could poll your inbox at certain intervals.
精彩评论