Posting articles by Email

Have you ever wanted to be able to post articles to your blog or to the news section on your site from email? This article will describe the process of developing just such a feature.

The only requirement for this is that your PHP be compiled with imap. You can determine if it is by going to the Reports -> System Info menu item, and viewing the "phpinfo" link.

imap-enabled

More information about PHP and IMAP can be found in the PHP documentation.

We can also create a mailbox dedicated to our purpose; this would make things much easier, although any existing mailbox could also be used. We'll use a very specific subject line to indicate an email to be posted.

Connecting to the Server

A few variables need to be set in the beginning, then the connection (in this case to the IMAP server) opened:

$uname = 'mail@domain.com'; // mailbox login
$upass = 'password'; // mailbox password
$mailserver = 'mail.domain.com'; // mail server name, or use localhost
$parent = 3; // the ID of the parent document for these documents
// connect to the mail server
$mbox = imap_open("{localhost:143}INBOX", $uname, $upass);
$total = imap_num_msg($mbox);
echo $total; // if you get a number here, you're in business!!

Browsing the Mail

Now we can dig into our mailbox and find what we're looking for. Suppose we decide to make our subject line "Submission". We can do a search in our mailbox for all messages with that subject line, then loop through the array to display the message bodies:

$listing = imap_search($mbox, "SUBJECT Submission");
foreach($listing as $msg) {
    $message = imap_body($mbox, $msg);
    echo "Message #$msg: $message<br />";
}

And here is what you get.

Parsing the Messages

The interesting part has been done. Now it's just a matter of replacing the display of the messages with code for parsing them, setting up the queries and inserting the data into the database.

to be continued...