Did you ever think about how an email group works behind the screen? You send an email to an email address(a unique email address dedicated to an email group). It is being saved and shown on the email group’s web page and also sent out to all email addresses which are members of this group. So, you will need to process the email contents to save them to DB, publish them on the webpage and send emails to others.
How PHP Email Piping Works:
In this tutorial, I will try to demonstrate the main part of a similar application as follows, how you can send an email’s content/information to a PHP handler on a Linux server and how we can parse the email contents into necessary parts like sender/subject/content etc. So, in this pipe email to PHP tutorial, we are going to do the following two tasks briefly:
Forward an email to a PHP script.
Retrieve the necessary contents by PHP.
Forward an email to a PHP script:
This part is the pretty straight way and doesn’t involve any coding. However, your hosting may or may not support this feature, so make sure first and contact support if not supported to know whether there is any way to do so(maybe by upgrading the hosting package, etc).
Firstly, log in to your hosting cpanel(Screenshots here are from host-gator).
Then, find the main section where you should see one option named ‘Forwarder’ or similar. Enter this section. And then click on the ‘Add forwarder’ button.
This section provides you with the option to do several actions whenever an email reaches an address it handles. We will be using the “Pipe to a program” option, which is the only option to forward it to a PHP script (Just to mention, you can use other languages too, not necessarily PHP, as long as that language is supported in your server). On this option, you will have to enter the path to the PHP handler file. Here carefully remember three things:
If you enter the PHP script’s URL here, it won’t work. You have to provide the local path location.(like “public_html/handlers/email_handler.php” or something like it).
You should specify the PHP compiler path(like “/usr/bin/php”) at the beginning.
You must need to make sure that the handler file has ‘execute’ permission. Otherwise, this command won’t be executed at all.
So basically, your command string here will be like a terminal command. One example is as follows:
First, we need to get the contents. To do so, on your handler PHP file, please add the following directive at the very top of the page(it may vary for you, refer to the previous section, need the path of PHP compiler correctly):
After the execution of the above code snippet, we will receive the full content in the “$email_content” variable.
Ok, so as we are now ready to get the contents from email, we can move ahead to parse it as you will receive the contents in some wired manner, not every piece differently. Wanna see what it looks like? Here are an example 🙂 :
Return-path: <senderemail@domain.com>
Received: from mail-wy0-f179.google.com ([74.125.82.179]:53218)
by gator526.hostgator.com with esmtps (TLSv1:RC4-SHA:128)
(Exim 4.69)
(envelope-from <senderemail@domain.com>)
id 1Qetnx-00061q-E5
for recieveremail@domain.org; Thu, 07 Jul 2011 14:00:05 -0500
Received: by wyh21 with SMTP id 21so939158wyh.38
for <recieveremail@domain.org>; Thu, 07 Jul 2011 12:00:06 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=gamma;
h=mime-version:date:message-id:subject:from:to:content-type;
bh=aVvn1hmmUfdWAswRt69lpHB1V8XJtvcueoBNWIIKkV8=;
b=o1jHeVKd8ollKyXuUlTpCG+DIS8eY1qoueyTaSYTyEqIFgiynuoX1NXTKzT9+l8SU/
LCqUoNYxofOtjNhkhJ7wS5mOQvoZVEnMyONTwRrx024PJE4/Do5VLltwNjPRzqMrFPux
otJCyqSddue/SGlTPxbBXiFsD7Gzl3TcTTdz8=
MIME-Version: 1.0
Received: by 10.216.237.131 with SMTP id y3mr7444080weq.87.1310065206713; Thu,
07 Jul 2011 12:00:06 -0700 (PDT)
Received: by 10.216.237.170 with HTTP; Thu, 7 Jul 2011 12:00:06 -0700 (PDT)
Date: Fri, 8 Jul 2011 01:00:06 +0600
Message-ID: <CAAxg_qAWbasvps0Q-2FAjXZ73zWzMErztqp5U_aUYUTCsxP6LQ@mail.domain.com>
Subject: [Demo - Test Group] Test topic 6
From: "Sender Full Name" <senderemail@domain.com>
To: Email Group <recieveremail@domain.org>
Content-Type: multipart/alternative; boundary=0015175cfc46475cbc04a77f53d6
--0015175cfc46475cbc04a77f53d6
Content-Type: text/plain; charset=ISO-8859-1
another new test topic.
--
Regards
Rana
--0015175cfc46475cbc04a77f53d6
Content-Type: text/html; charset=ISO-8859-1
<brclear="all">another new test topic.<br>-- <br>Regards<br><br>Rana<br>
--0015175cfc46475cbc04a77f53d6--Code language:HTML, XML(xml)
So, how is it? Do you like it? Hope not; I didn’t like it at all :D. So, what we need now, is to parse it. Well, though you can do it yourself by spending some time, here is some ready-made code that you can reuse all the time. Here we go:
//split the string into array of strings, each of the string represents a single line, received
$lines = explode("\n", $email_content);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each linefor ($i=0; $i < count($lines); $i++) {
if ($is_header) {
// hear information. instead of main message body, all other information are here.
$headers .= $lines[$i]."\n";
// Split out the subject portionif (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portionif (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// content/main message body information
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$is_header = false;
}
}Code language:PHP(php)
So, after this, in the end, you should get from, to, subject, and message information in their corresponding variables.
Final Words:
Remember, your message body structure will differ a bit from one email client to another. So, you will have to take care of the client you are using. If you want to support most of the clients(yahoo/google/Hotmail), you may have to apply several parsing rules on the message to get text and/or HTML version.
To debug how it’s working, you can’t do it on the browser as the contents will go from email, so you should use logging on an external text file and write a log about each step and error to get full details.
Hopefully, this pipe email to PHP tutorial will help you understand how the process works. That are just the basic parts(most important, though 🙂 ) of the way to build an email group. Let me hear if you have any questions. Happy coding 🙂
I added an insert statement to drop the data from the email message including email address etc into a MySQL DB – but I get a bunch of unwanted stuff in the database appearing in the ‘message’ column which looks like headers of the email like this:
You will need to filter them with regular expression as far I can suggest. Don’t see any other way around atm, email contents usually do have such lots of unnecessary characters for formatting probably, which differs from client to client(yahoo/gmail/outlook etc).
I have my text in spanish but when I answer the mail with outlook, I get unwanted characters where I use spanish accents á ú í é ó and in the line breack I get =20, can you give me a hint on how can I replace this charaters with the vocals and with the accent again ?
thanks for your help
Hello! I know this post is a little bit cold… but I wonder if you might help? I have implemented this code, and it works with one exception… each time a mail is successfully parsed i get 7 mails.
The processing i have programmed is supposed to identify the subject, and then add that as the body of a mail to my office email address.
only I get 7 identical emails!
Any thoughts or direction would be much appreciated!
You can put something like “/path/to/domain/index.php/controller/method” easily to get it working. Just imagine, .htaccess won’t have any effect as this is not going through Apache server, rather direct access.
I have implemented the script and it is working fine. The only issue is that I am trying to send an email back to the sender with an output text file of the parsed info as an attachment. The output text file looks good, however the sender is receiving the email without the attachment.
Is it possible to send an attachment email from the script itself since the sending email part with attachment works when executed separately ?
Thank you for this. It worked great for me except I can’t figure out why I can’t write any of the details to a file. I’m guessing that maybe there’s something unexpected with the file path? My script is in public_html/my_folder/pipescript.php and I’m trying to write in to a text file in public_html/my_folder/files/
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
sunil kumar says
Thanks for your good solution.
Rob Chadwick says
Thanks! This was very useful.
Stewart says
Very good, thanks.
I added an insert statement to drop the data from the email message including email address etc into a MySQL DB – but I get a bunch of unwanted stuff in the database appearing in the ‘message’ column which looks like headers of the email like this:
“This is a multi-part message in MIME format.
——=_NextPart_000_0101_01CEAA6E.6A79E160
Content-Type: text/plain;
charset=”iso-8859-1”
Content-Transfer-Encoding: quoted-printable
I also see quotes appearing in the other columns – how to get rid of any unwanted characters?
Md Ali Ahsan Rana says
You will need to filter them with regular expression as far I can suggest. Don’t see any other way around atm, email contents usually do have such lots of unnecessary characters for formatting probably, which differs from client to client(yahoo/gmail/outlook etc).
alby says
I have my text in spanish but when I answer the mail with outlook, I get unwanted characters where I use spanish accents á ú í é ó and in the line breack I get =20, can you give me a hint on how can I replace this charaters with the vocals and with the accent again ?
thanks for your help
AATIF says
NICE OWRK
Alex Whyatt says
Hello! I know this post is a little bit cold… but I wonder if you might help? I have implemented this code, and it works with one exception… each time a mail is successfully parsed i get 7 mails.
The processing i have programmed is supposed to identify the subject, and then add that as the body of a mail to my office email address.
only I get 7 identical emails!
Any thoughts or direction would be much appreciated!
cheers
LAex
Ashok Singh says
Hi ,
Thanks for the post. It’s realy useful. I have implement this functionality and It’s working fine.
Regards,
Ashok Singh
Tshepo says
Hi,
How can I use this to also retrieve attachments from the email?
Regards,
krishnalal says
How can add forwaders path to capanel in framework codeigniter
Md Ali Ahsan Rana says
You can put something like “/path/to/domain/index.php/controller/method” easily to get it working. Just imagine, .htaccess won’t have any effect as this is not going through Apache server, rather direct access.
Esayed says
I have implemented the script and it is working fine. The only issue is that I am trying to send an email back to the sender with an output text file of the parsed info as an attachment. The output text file looks good, however the sender is receiving the email without the attachment.
Is it possible to send an attachment email from the script itself since the sending email part with attachment works when executed separately ?
parthpabariParth says
how to get attachments files??
Robert says
Is it possible to pipe emails of a gmail account?
Thank you
Naveed Fakhar says
first of all forword gmail to privet email where forword command existed then you will get, if you want dirctilly its log procedure
dany says
How to get exact messages and images? let me know..
Aagii says
How can I pipe to Laravel Controller? Please, help.
Tarek O says
It did not work for me
ld13 says
What did not work for you? Need something more verbose to assist…
John Hoskinson says
Thank you for this. It worked great for me except I can’t figure out why I can’t write any of the details to a file. I’m guessing that maybe there’s something unexpected with the file path? My script is in public_html/my_folder/pipescript.php and I’m trying to write in to a text file in public_html/my_folder/files/
so I have a code like this:
$File = “files/text-file.txt”;
$Open = fopen($File, “a+”);
fwrite($Open, “$message”);
fclose($Open);
I send a test email, I get the message back in the body as expected, but nothing writes to the file.
Any suggestions?
Jaydip Shingala says
Hello, It resolved my problem.
Thanks