How do I receive email and process it in a web application
I recently worked on a project that required parsing of email from gmail and updating database with certain values based on the contents of the email. I used the ezcMail (now) Zeta Components library to connect to the mail server and parse the emails.
The strategy I adopted was to filter all interesting incoming mail with a label "unprocessed". Run the PHP script via a crontab every 15 minutes. The script would connect to the mail server and open the IMAP unprocessed folder and parse each email. After inserting the interesting values into the database, the script moves the files to another IMAP folder "Proccessed".
I also found IMAP to be better than POP for this sort of processing.
Recently I wanted to be able to receive emails immediately in something I was making so I did some research (I came looking on this question here too actually) and I ended up finding Google App Engine to be pretty helpful. It has an api you can use to receive and process emails sent to [email protected]
. I know that it doesn't really seem helpful since you probably don't want your app on App Engine and you want to receive emails at yourdomain.tld, but with a little setup you can get what you want.
My basic setup is like this:
- User sends email to [email protected] (an email address that doesn't actually exist)
- mydomain.tld has a catchall email address that forwards to [email protected]
- GAEapp (a tiny app on app engine) receives the email, processes it out, and sends a post request with relevant stuff to mydomain.tld
So basically you can make a little GAE app that works like a go between to grab the emails. Even with the redirect it'll work out ok, the email will be fine.
Also I decided to learn me some django and I made a free app called Emailization that will basically do that for you. You create a recipient like [email protected]
and give a URL to POST to. Anything sent to that address gets POSTed to you URL. You can make a catchall on your domain that forwards to that emailization recipient and you'll get email through the catchall too!
or you can see a small GAE app I made that you can setup yourself that does the same thing.
Hope that helps somebody!
Use procmail if it is installed on your system. Put these lines in a .procmailrc file in the home directory of the user who receives the e-mail.
:0
| /path/to/your/script.php
Or you can also use a .forward file containing
"|/path/to/your/script.php"
Procmail has the advantage that it allows you to deal with more complicated filtering if your application ever requires it.
Your script.php file will read the headers and body of the e-mail from stdin.
Check out fMailbox. It does not require any non-standard extensions (such as imap) and has been tested with various servers, attachments, multipart messages, SSL, and more.