Brendan Dawes
The Art of Form and Code

A Simple Email to Blog Gateway for Kirby

When I write a blog post on this site it begins by creating a Kirby formatted text file inside a newly created directory which I then upload to my server. Yet sometimes I want to just make a note of a website, or just blog a quick thought and having to do all of the above to make a simple post seems like a lot of work. I remember a service called Posterous (now long dead) that let you create blog posts purely be email. It worked really well, so I thought I'd use the powers of IFTTT with a simple php script to create something similar.

Email Format

First let's look at how I format my emails for the system.

In the subject I put what I want the title of the blog post to be. Following that I then put a hashtag that is either #bookmark or #article. This is so I can change how the email is processed, which you'll see in a moment.

If I'm simply posting a bookmark then I make the first line of the email the URL I want to post. On the following line I put four pound signs. This acts as a delimiter for the URL. On the line after that I put a description of the URL.

The bookmark version of the email looks like this:

Subject: Title of the link #bookmark
Body:   http://somelink.com
    ####
    A description of what the bookmark is.

If I want to simply create a regular article post, the subject hashtag is #article and the body of the email is just regular text, no need for a delimiter.

PHP Script

The core part of the system is a PHP script that sits on my server and handles information passed to it via IFTTT. Below is that script which I've tried to comment as much as I can.


<?php
// include Kirby
require($_SERVER['DOCUMENT_ROOT'] . '/kirby/bootstrap.php');

// include a non-web accessible config file containing IFTTT_PASS and SALT
include 'path/to/your/config/file.inc';

// check to see if the passed in udid parameter plus SALT matches our config file and check body of email is not blank
if(get('udid').$SALT==$IFTTT_PASS.$SALT && get('body')!=="") {

    // get the articles
    $articles = page('blog')->children();
    // create an index number based on number of articles
    $index     = ($articles->count() + 1);
    // store the date
    $date     = date('Y-m-d H:i:s');
    // create the directory name to store the post
    $dirname  = $date . '-' . $index;
    // get the body of the email
    $body = urldecode( get('body'));
    // get the title of the post from the subject
    $title = urldecode( get('subject'));
    // get the type of post - either bookmark or article
    $type = urldecode( get('type'));

    // if type bookmark
    if ($type=="bookmark") {
        // get the url
        $url = getUrls($body);
        // create the href for the url
        $link = '<a href="'.$url.'">'.$title.'</a>';
        // get the delimiter index
        $delimiter = strpos($body,'####');
        // get the body text after the delimiter
        $body = substr($body,$delimiter+4,strlen($body));
        // create the text for the post
        $text .= $link.'<p></p>'.$body;
        // create the content for the post
        $content  = array('title'  => $title, 'date'   => $date, 'text'   => $text,'blogid' => $index, 'tags' => 'Bookmark');
        // if the URL is not blank then save the post in the directory  as specified in $dirname with the filename 'article' 
        if ($url !== "") {
            $article  = $articles->create($dirname, 'article',$content);

        }
    }
    // if type article
    if ($type=="article"){
        // create the content
        $content  = array('title'  => $title, 'date'   => $date, 'text'   => $body,'blogid' => $sort, 'tags' => 'Process');
        // create the article as before
        $article  = $articles->create($dirname, 'article',$content);
        // if there is an attachment such as an image then download it and save it
        if (get('attachment') !=="") {
            downloadImage(get('attachment'),$_SERVER['DOCUMENT_ROOT'].'/content/05-blog/'.$article->dirname().'/image.jpg');
        }
    }
} else {

    echo('UDID NOT VALID');
}

function getUrls($string) {
    $regex = '/https?\:\/\/[^\" \n]+/i';
    preg_match_all($regex, $string, $matches);
    $url = $matches[0][0];
    $s1 = substr($url, 0, strlen($url));
    return $s1;
}

function downloadImage($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');              // open file handle
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);
    curl_close($ch);                              // closing curl handle
    fclose($fp);                                  // closing file handle
}

?>

Set Up IFTTT

The final part is to setup IFTTT to handle transferring emails to your script which in turn makes the blog post.

On ifttt.com create a new Applet with the trigger "Send IFTTT an email tagged".

After choosing this you'll be asked to choose a tag — in my case I chose #boomark or #article. Then click Create Trigger.

For the THAT section choose Webhooks. Choose the only option — the Make a web request option.

In the URL field put the URL to the php script you created using the script above. In the method choose POST. Set the content type to form-urlencoded.

Add this to the Body field:

subject=<<<{{Subject}}>>>&body=<<< {{Body}}>>>&udid=<YOUR_UDID>&type=<NAME_OF_HASHTAG>&attachment={{AttachmentUrl}}

Change the UDID to match your secret UDID the php script uses to make sure the request is genuine. Change NAME_OF_HASHTAG to be the hashtag so it matches the tests we do in the php script from earlier, for instance "bookmark" or similar.

Click save and your new email to blog system is ready to try. When you send an email to trigger@applet.ifttt.com with the correct hashtag in the subject field it will call the php script, check the credentials match and then make a blog entry for you, all being well.

This is a pretty basic system, but it works and might be something you can build on.