Triggering a file on arrival of a email

From HelioHost Wiki
Jump to: navigation, search

Preface

This thread is based a forum post by Krydos

Setup

Go to "Email accounts" in your cPanel and create the email address we're going to use in this tutorial.

For this example, we'll use admin@example.heliohost.org

Now go to "Email Filters" and click "Manage Filters" next to the email address we just created.

Click "Create New Filter". Name the filter "Pipe Test". For testing let's set it to trigger whenever the Subject contains the string "Pipe Test". Select "Pipe to a Program". In the box type:

|/home/example/email/email_handler.php

That first character is a pipe which is a vertical line. If you want the email to be delivered to your inbox in addition to piping to your script you can click the + on the right side, and set up Deliver to Folder: Inbox. This way it'll pipe it to your script AND put it in the inbox.

Create
/home/example/email/email_handler.php
with permissions 755. The first two lines are very important. The first line has to be the shebang which is #! and then the path to the PHP version you want to use. The -q flag suppresses the output of php headers. If you echo any output of any kind in your script it will be emailed back to the sender as an error. This includes headers. The second line has to be <?php There can't be any blank lines or random characters or windows line endings. Any of that stuff will mess it up.
#!/opt/cpanel/ea-php71/root/usr/bin/php-cgi -q
<?php
 
// listen for incoming emails
$sock = fopen("php://stdin", "r");
$email = "";
 
// read email into buffer
while (!feof($sock)) {
  $email .= fread($sock, 1024);
}
 
// close socket
fclose($sock);
 
// log received email
$file = "/home/rutaj6/email/email.log";
$fh = fopen($file, 'a');
fwrite($fh, "$email\n\n\n");
Create
/home/example/email/email.log
with permissions 644.

Now send an email to yourself at admin@example.heliohost.org and make sure "Pipe Test" is in the subject line to trigger the filter.

If everything worked it should write your email to /home/example/email/email.log. From there the sky is the limit. You can process this raw input as much as you want and do whatever.

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox
Google AdSense