CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming Pipe Email To PHP And Parse Content

Pipe Email To PHP And Parse Content

Rana Ahsan December 22, 2011 19 Comments


 Pipe Email To PHP And Parse Content    

Did you ever think how an email group works, on behind the screen? You send an email to an email address(a unique email address dedicated to an email group), then it is being saved and show on the email group’s web page, and also sent out to all email addresses who are member of this group. So, basically, you will need to process the email contents to save them to db, publish on webpage and send email to others.

How PHP Email Piping Works:

On this tutorial, I will try to demonstrate the main part of similar application as follows, how you can send an email’s content/information to a php handler on 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 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 any way to do so(may be by upgrading the hosting package,etc).

Firstly, login to your hosting cpanel(Screenshot here are from host-gator).
Hostgator Cpanel Email Section
Then, find the mail section where you should see one option named ‘Forwarder’ or similar. Enter to this section. And then click on the ‘Add forwarder’ button.
Adding Email Forwarder
This section provides you option to do several actions whenever an email reaches to 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:

/usr/local/bin/php -q /home/yourdomain/public_html/handlers/mail_to_group.php 

Retrieve necessary contents from email by php:

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):

#!/usr/local/bin/php -q

This won’t be under php tag at all, will be outside. php tag should start after it.

Now, the following code snippet will retrieve the full content received:

$fd = fopen("php://stdin", "r");
$email_content = "";
while (!feof($fd)) {
$email_content .= fread($fd, 1024);
}
fclose($fd); 

After the execution of 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 how it look like? Here is 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

<br clear="all">another new test topic.<br>-- <br>Regards<br><br>Rana<br>

--0015175cfc46475cbc04a77f53d6--

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, but here is some ready-made code that you can reuse all the times. 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 line
for ($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 portion
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portion
if (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;
}
}

So, after this, at the end, you should get from, to, subject, message information in their corresponding variables.

Final Words:

Remember, your message body structure will may 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 rule on the message to get text and/or html version.

To debug how its working, you can’t do on browser as the contents will go from email, so you should use logging on an external text files and write log about each step, errors to get full details.

Hopefully, this pipe email to php tutorial will help you understand how the process works. That is just the basic parts(most important though 🙂 ) in the way to build an email group. Let me hear if you have any question. Happy coding 🙂

Related

Filed Under: Programming Tagged With: php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. sunil kumar says

    October 11, 2012 at 11:48 pm

    Thanks for your good solution.

    Reply
  2. Rob Chadwick says

    May 11, 2013 at 6:23 pm

    Thanks! This was very useful.

    Reply
  3. Stewart says

    September 5, 2013 at 12:44 pm

    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?

    Reply
    • Md Ali Ahsan Rana says

      September 30, 2013 at 1:36 pm

      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).

      Reply
  4. alby says

    October 31, 2013 at 6:15 pm

    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

    Reply
  5. AATIF says

    November 2, 2013 at 3:11 am

    NICE OWRK

    Reply
  6. Alex Whyatt says

    January 26, 2014 at 1:30 pm

    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

    Reply
  7. Ashok Singh says

    August 29, 2014 at 3:17 am

    Hi ,

    Thanks for the post. It’s realy useful. I have implement this functionality and It’s working fine.
    Regards,
    Ashok Singh

    Reply
  8. Tshepo says

    October 11, 2014 at 11:32 pm

    Hi,

    How can I use this to also retrieve attachments from the email?

    Regards,

    Reply
  9. krishnalal says

    February 26, 2015 at 10:01 pm

    How can add forwaders path to capanel in framework codeigniter

    Reply
    • Md Ali Ahsan Rana says

      February 27, 2015 at 1:53 pm

      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.

      Reply
  10. Esayed says

    June 1, 2015 at 7:22 am

    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 ?

    Reply
  11. parthpabariParth says

    September 14, 2015 at 4:10 am

    how to get attachments files??

    Reply
  12. Robert says

    June 10, 2017 at 5:53 am

    Is it possible to pipe emails of a gmail account?
    Thank you

    Reply
  13. dany says

    February 16, 2018 at 1:14 am

    How to get exact messages and images? let me know..

    Reply
  14. Aagii says

    February 29, 2020 at 4:50 pm

    How can I pipe to Laravel Controller? Please, help.

    Reply
  15. Tarek O says

    March 16, 2020 at 5:25 pm

    It did not work for me

    Reply
    • ld13 says

      June 11, 2020 at 7:52 am

      What did not work for you? Need something more verbose to assist…

      Reply

Trackbacks

  1. Useful Git Commands List | codesamplez.com says:
    January 19, 2012 at 2:02 am

    […] Before, I have discussed about very very basics about git and about github. However, none of those tutorials covered the important git commands that is usually needed. I will […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • How To Work With Codeigniter Caching In PHP
  • LinQ Query With Like Operator
  • Getting Started With HTML5 Web Speech API

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in