News

Automated E-mail Handling with Cpanel

Written by UI-Staff

Many of our clients at Urban Influence are hosted on servers which run WHM or CPanel. I recently had an opportunity to utilize a feature of Cpanel which I had not previously used – the ability to process an incoming email message with a script.

This is extremely handy in situations where you need to accomplish an automated task, such as updating a message thread, via email. Let's say for instance that when Jane, a user of my web application, sends an email to at [email protected], I want to process her message and add it to a message thread displayed in my web application. I can accomplish this by following these steps.

1. Create an Email forwarder

In CPanel, you can create a mail forwarder which will respond to a received email. To do this, click on Forwarders in your CPanel menu. Then click on 'Add Forwarder'.

2. Set up the script which will intercept your email

Once you reach the "Add new forwarder" screen, you can elect to pipe the message to a program. My version of Cpanel looks like this:

Simply enter the path of the script which will handle the email (relative to your home directory) in the text box. Now whenever mail is received at this address, it will be forwarded onto your script.

3. Write your interpreter script

We can now interpret the email message in our script and process accordingly. For my program, I needed to pass this message to a ruby script which would extract a file attachment and upload it to another location. In ruby, your script might look something like the following:

#!/usr/local/bin/ruby     # – a hash bang line, which tells the server where 'ruby' lives
require 'rubygems'  #- a link to my rubygems libraries
require 'iconv'  #  – a library for converting file formats

# Some additional app-specific libraries
require File.dirname(__FILE__) + '/lib/email_reader.rb'
require File.dirname(__FILE__) + '/lib/alert_mailer.rb'

# Download attachment from email piped to this program
email_reader = EmailReader.new(ARGF.read)

The require statements above will load different libraries I need to interpret the program. The real work comes at the ARGF.read statement – which is where the entire email content is read. In this example, I'm just taking that text and passing it to a class I've created for parsing emails.

This example can easily be modified to work with the programming language of your choice.