Web Hosting Forum | Lunarpages


*
Welcome, Guest. Please login or register.
Did you miss your activation email?



Login with username, password and session length
May 22, 2012, 08:33:15 PM

Pages: [1]   Go Down
  Print  
Author Topic: How to Setup a PHP Script to Execute after Receiving an E-mail  (Read 1771 times)
jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« on: October 23, 2007, 03:05:42 PM »

Hello.  So, I have like 10 cron jobs.  Each one is a PHP script that runs every five minutes or so.  I think it's kind of inefficient, and was wondering if there's a better way.  Is it possible to rig something up so that every time an e-mail is sent to a specific e-mail address, a corresponding PHP script is run?  Thanks in advance for your help.

Jeff
Logged
JimBrown
Knowing enough to be dangerous!
Jabba the Hutt
*****
Offline Offline

Posts: 743



WWW
« Reply #1 on: October 24, 2007, 02:24:25 PM »

Yes, it is possible. You want to set up an email filter to grab the message, and then set the destination as a pipe to your script. The destination would look like this:

Code:
|/home/<cpanelusername>/path/to/script.php
(The first character above is the "pipe" symbol (vertical bar) "|")

The very first line of your PHP script must be this:

Code:
#!/usr/bin/php -q

If you wish the script to read in the contents of the email, use this:

Code:
$fp = fopen("php://stdin", "r");

while (!feof ($fp)) {
  $line = fgets($fp);
.
.
Do stuff here
.
.
}

Yes, I have such a set up, and it works for me.

Have fun!
...jim
« Last Edit: October 24, 2007, 02:26:24 PM by JimBrown » Logged

MrPhil
Senior Moderator
Berserker Poster
*****
Offline Offline

Posts: 5203



« Reply #2 on: October 24, 2007, 04:38:16 PM »

JimBrown, that sounds like something that would at least partially answer my questions raised in this posting. Now, is this only permitting you to read an email that just came in, but not delete or modify it, or can that be done too? I'm still wondering if there is a general purpose tool kit to handle mail and filter/forward/edit it or take other actions (e.g., raise an alarm or send emails based on the content). Has no one written up such a thing because it would break with every change to the mail system?
Logged

Visit My Site

E-mail Me
  
-= From the ashes shall rise a sooty tern =-
jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #3 on: October 25, 2007, 03:16:30 AM »

OK, so I'm stumped.  I did what you said, but I just can't get it to work.  I set up an e-mail filter through cPanel so that every e-mail sent to a specific e-mail address forces a PHP script to be called, but every time I send an e-mail to that address, I get an e-mail saying "(Mail delivery failed: returning message to sender) This message was created automatically by mail delivery software.  A message that you sent could not be delivered to" (it gets cut off there).

For the destination, I entered: |/home/MYUSERNAME/CronJob_BreakingNews.php
For the e-mail address, I entered something like this: account@domain.com

The PHP script starts with:

#!/usr/bin/php -q

<?php

(and then goes into the rest of the script)

?>

Any ideas?
Logged
MrPhil
Senior Moderator
Berserker Poster
*****
Offline Offline

Posts: 5203



« Reply #4 on: October 25, 2007, 09:56:56 AM »

For the destination, I entered: |/home/MYUSERNAME/CronJob_BreakingNews.php

Is that really where your PHP script is? Are you missing public_html/ in there? I don't know if the mail system filtering requires your PHP script to be under the public_html/ tree -- since you give the complete path starting at /home, I would guess that it could be anywhere, but perhaps not. Jim?
Logged

Visit My Site

E-mail Me
  
-= From the ashes shall rise a sooty tern =-
jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #5 on: October 25, 2007, 12:35:09 PM »

I tried moving the file to my public_html folder and changing the destination just to be thorough and rule that out, but the same thing happened.
Logged
JimBrown
Knowing enough to be dangerous!
Jabba the Hutt
*****
Offline Offline

Posts: 743



WWW
« Reply #6 on: October 25, 2007, 02:14:56 PM »

The script can reside wherever you wish (best bet is somewhere not available to a browser, which means not in public_html.)

I forgot to mention that the script needs the execute bit set. Check the permissions and ensure they are set to 755. (Exim executes the script itself in a shell. The first line tells the shell what program to use to run the script. This is different from a web page php file, which Apache just reads in and sends the php commands to php. A web page php file is not executed.)

MrPhil, sorry but I have not done anything more than have my script gobble up the email, place some info contained in the email into a database, and create an ack email back to me. The original email goes no futher than the being eaten by the script.

Regards,
...jim
Logged

jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #7 on: October 25, 2007, 02:46:56 PM »

Hmmm... I tried setting it to 755 and I keep getting the same error.  Ideas?
Logged
JimBrown
Knowing enough to be dangerous!
Jabba the Hutt
*****
Offline Offline

Posts: 743



WWW
« Reply #8 on: October 27, 2007, 08:20:42 AM »

Hmmm...

Are you using an email filter, or an email forwarder? Either way will work, but the set up is slightly different.

And, in your case, if you wish to trigger the script when a message is sent to a specific email address, then using an email forwarder would be the better method.

To use a forwarder, go to "Mail" -> "Forwarders" in cPanel. At the bottom click on "Add Forwarder".  In the first box enter the "username" of the email address (the part before the "@" sign) of the message you wish to use to trigger the script. Select the domain you wish to use in the drop down list. In the box to the far right, enter the destination as mentioned above, "|/home/USERNAME/path/to/script.php" (without the quotes, and replace USERNAME with your cPanel username.) Finally, click "Add Forwarder".

If you previously set up an email filter, don't forget to delete it.

If you do not need to save the message, do not set up a mailbox for the email address you wish to use.

Regards,
...jim
Logged

jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #9 on: October 27, 2007, 01:59:54 PM »

At first, I was using an e-mail filter, and I did some Googling, and then decided to try an e-mail forwarder.  I've tried using the pipe command "|/home/myusername/ScriptFilename.php" with the first line of code in that file being "#!/usr/bin/php -q" and the permissions set to 755, but that has not worked for me.  I keep getting the same error message:

This message was created automatically by mail delivery software.

A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:

  pipe to |/home/MyUsername/ScriptFilename.php
    generated by email@mydomain.com
    local delivery failed

The following text was generated during the delivery attempt:

------ pipe to |/home/MyUsername/ScriptFilename.php
      generated by email@mydomain.com ------

Error in argument 1, char 3: option not found
Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]
      php <file> [args...]
  -a              Run interactively
  -C              Do not chdir to the script's directory
  -c <path>|<file> Look for php.ini file in this directory
  -n              No php.ini file will be used
  -d foo[=bar]    Define INI entry foo with value 'bar'
  -e              Generate extended information for debugger/profiler
  -f <file>        Parse <file>.  Implies `-q'
  -h              This help
  -i              PHP information
  -l              Syntax check only (lint)
  -m              Show compiled in modules
  -q              Quiet-mode.  Suppress HTTP Header output.
  -s              Display colour syntax highlighted source.
  -v              Version number
  -w              Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.


So, I keep getting that error, and the script does not execute.  Not sure why.  However, I did do a little more searching, and tried a different pipe command.  I tried this: "|/usr/bin/php /home/MyUsername/ScriptFilename.php -q", and it worked.  The script executes, but I still get an error message (this time it is different).  Here it is:

This message was created automatically by mail delivery software.

A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:

  pipe to |/usr/bin/php /home/MyUserName/ScriptFilename.php -q
    generated by emailaddress@mydomain.com

The following text was generated during the delivery attempt:

------ pipe to |/usr/bin/php /home/myusername/ScriptName.php -q
      generated by emailaddress@domain.com ------

X-Powered-By: PHP/4.4.4
Content-type: text/html


So, the good news is the script works.  But the error message is kind of annoying, and I don't really know what it means.  I haven't actually gotten to the point where I actually do anything with the e-mail yet, so I'm not sure if that even works.  But I've gotten this far... any ideas?
Logged
jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #10 on: October 27, 2007, 04:33:00 PM »

OK, so I've been fooling around with it a little more.  There are only two remaining issues.
1.  Getting rid of the error message
2.  Figuring out a way to extract the subject and body from the text below:

From you@yours.com Sat Oct 27 16:20:33 2007
Received: from web56208.mail.re3.yahoo.com ([216.252.110.217])
    by circini.lunarpages.com with smtp (Exim 4.63)
    (envelope-from <you@yours.com>)
    id 1IluxF-0003b7-De
    for mine@ours.com; Sat, 27 Oct 2007 16:20:33 -0700
Received: (qmail 51740 invoked by uid 60001); 27 Oct 2007 23:20:31 -0000
DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws;
  s=s1024; d=yahoo.com;
  h=X-YMail-OSG:Received:X-Mailer:Date:From:Subject:To:MIME-Version:Content-Type:Message-ID;
  b=DWeR+s6O7/Gg5M/2jxu6VJYDlBz12b+SN/UtXnClu2LmTr3hTmF9YFHvYrJF7+zThuxC+84nyzbJQQ2kbE74oNk0ixKkf3eGhk1b+UqvzQ9qV/ezqwXygYJ+DwUtoWEg8DF1afL2qg3ARtiFIsNqHmHVkDLpHDWK6qMg/XXp8rs=;
X-YMail-OSG: nRg45v8VM1nvxVfMcXRiKRPqrE0sToTZ_Mk3y7jFc.8zlYu_ASibUH.sA7TsXgy5aj6lyfOBXcbNVni2xqBnHTB7FLSKRfbYwSJvdwj_O.S56IDlRJ8-
Received: from [x.x.x.x] by web56208.mail.re3.yahoo.com via HTTP; Sat, 27 Oct 2007 16:20:31 PDT
X-Mailer: YahooMailRC/814.06 YahooMailWebService/0.7.152
Date: Sat, 27 Oct 2007 16:20:31 -0700 (PDT)
From: Jeff <you@yours.com>
Subject: Subject
To: mine@ours.com
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="0-456948925-1193527231=:51112"
Message-ID: <768879.51112.qm@web56208.mail.re3.yahoo.com>

--0-456948925-1193527231=:51112
Content-Type: text/plain; charset=us-ascii

Body



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
--0-456948925-1193527231=:51112
Content-Type: text/html; charset=us-ascii

<html><head><style type="text/css"><!-- DIV {margin:0px;} --></style></head><body><div style="font-family:arial,helvetica,sans-serif;font-size:12pt"><div>Body<br></div></div><br>__________________________________________________<br>Do You Yahoo!?<br>Tired of spam?  Yahoo! Mail has the best spam protection around <br>http://mail.yahoo.com </body></html>
--0-456948925-1193527231=:51112--


Are there any PHP functions for extracting these things from a string like this?  Thank you in advance for your help.  I know I couldn't have gotten this far without you!
Logged
JimBrown
Knowing enough to be dangerous!
Jabba the Hutt
*****
Offline Offline

Posts: 743



WWW
« Reply #11 on: October 28, 2007, 07:55:29 AM »

Regarding the error message. Try this: Change the destination back to without the -q at the end. In cPanel, go to the File Editor and open the script for editing. Go to the end of the first line. Backspace over the -q, then type it in again. Save the file.

I know, weird. But I recall having to do that if I uploaded the script from my home computer.

Regarding extracting the subject and body, use the php snippet I posted above to loop through each line looking for what you want. Something like this:

Code:
<?php
$fp 
fopen("php://stdin""r");

$getbody 0;
$body "";
while (!
feof ($fp)) {

  
# Grab a line from the message
  
$line fgets($fp);
  
  
# If it begins with Subject, grab the actual subject
  
if substr($line08) = "Subject:" {
    
$Subject substr($line9);
  }
  
  
# If the body has started, add the line to the body
  # Assumes that body will run to the end of the message.
  
if $getbody {
    
$body $body $line;
  }
  
  
# If it finds this text, then the body is about to start
  # This is after the body add bit so we don't add this to the body.
  
if $line "Content-Type: text/plain; charset=us-ascii" {
    
$getbody 1;
  }
}

# The subject is now in $Subject
# The body is now in $body

?>


Have fun!
...jim
« Last Edit: October 28, 2007, 07:57:27 AM by JimBrown » Logged

jzimmerlin
Spacescooter Operator
*****
Offline Offline

Posts: 44


« Reply #12 on: December 01, 2007, 06:48:23 PM »

The Solution

Here's how to make sure your e-mail forwarders work...
1.  The syntax for your destinations in cPanel should be as follows: "|/usr/bin/php -q /home/USERNAME/FILENAME.php" (minus the quotation marks of course).  The difference between this and what was discussed above is that the "-q" was moved from the end of the destination to directly after "|/usr/bin/php".

2.  The permissions on your PHP scripts do not necessarily need to be set to 755, 644 worked just fine for me.

3.  The beginning of your PHP scripts do not need to begin with "#!/usr/bin/php -q".

That's it!  Things may be different for you depending on the server that you're using, but doing these things made e-mail forwarders work for me on the new server Lunarpages migrated my web site to.

Good Luck!

Jeff
Logged
Pages: [1]   Go Up
  Print  
 
Jump to: