Categories: PHP

Store email reply to our database in php

Store email reply to our database in php

Store email reply to our database in php. I am using basecamp for my applications. When ever I add to d0 or updated to I will receive the email from basecamp with to do ID as reply email. If I give a reply It want to send email as well update in my basecamp to do. I felt its one of the cool stuff. If we are going to use comment system means these kind of features will add more flexibility to the users. After a long research found the solution to implement this logic.

There are may ways to achieve this. By using Mandrill or Sendgrid we can achieve this easily. We have php imap functionality which will read the incoming emails. By using this we can able to read incoming email for static given email id, We cannot make a dynamic email id based on post id. But by using mandrill we can implement this.

Lets see how to achieve this,

Step 1 : Create Mandrill account

Step 2 : Go to Settings [In left side bar] => Domains => Add your domain name

Mandril Settings

Mandrill Domain

Step 3 : Add DKIM Settings & SPF Settings TXT records in mentioned domains, By clicking View DKIM settings & View SPF settings you can see txn records => In My case I have domain in godaddy so added MX records under DNS management

DKIM Record

SPF Record

Step 4 : Click “Test DNS Settings” to check, the TXT records are added successfully or not. If you added successfully you can see green tick like my screen grab.

Step 5 : Click Inbound Menu at left side bar

Step 6 : Add your domain in below of Inbound Domains Text box

Step 7 : Click View Setup Instructions button on the top right

Step 8 : Add Showing both of the MX Records in your domain => In My case I have domain in godaddy so added MX records under DNS management

Step 9: Click Test DNS Settings button to check Mx records are added successfully or not

Step 10 : Click your added domain name to add webhook and click save

Webhook => It will post the inbound emails to given url

Step 11 : Click +Add New Route button

Step 12 : In Text box you can give static email address or global

For eg : *@domain.com // Global => It will redirect all emails for this domian to given url

For eg : info@domain.com // Global => It will redirect only info@domain.com emails for this domian to given url

Step 13 : Enter the URL where mandrill want to Inbound your emails

Step 14 : Write your code to fetch inbound email datas in your mentioned url file. In my case I am using PHP.

How to add dynamic id in reply-to email :

In our webhook email address we have mentioned as “*”, So what event the email before ******@yourdomain.com will read in your given webhook url . So Just create dynamic id and place it under header reply to email id.

Eg :

    $email = 'info-8765092-excsweawsfdkuex@yourdomain.com';
    $headers = 'From: myemail@my_domain.com' . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

Here in my case 8765092 is my post Id, So based on it will update my table.

How to get read inbound emails in PHP and Store in database

The below code was return in the page where we given webhook url.

Here I have stored read data in txt file as well as stored in DB

Read datas from web hook and store email reply to database

$mail = array_pop(json_decode($_POST['mandrill_events']));

mysqli_query($mysqli,"INSERT INTO reservation_messages (from_name, from_email, to_email, message, reservation_id, reply_to, subject) VALUES( '".$mail->msg->from_name."', '".$mail->msg->from_email."', 'testabc@gmail.com', '".$message."', 1, '".$mail->msg->email."', '".$mail->msg->subject."')"); 

$attachments = array();
foreach ($mail->msg->attachments as $attachment) {
    $attachments[] = array(
        'type' => $attachment->type,
        'name' => $attachment->name,
        'content' => $attachment->content,

$headers = array();
// Support only Reply-to header
if(isset($mail->msg->headers->{'Reply-to'})) {
    $headers[] = array('Reply-to' => $mail->msg->headers->{'Reply-to'});

$message = array(
        'html' => $mail->msg->html,
        'text' => $mail->msg->text,
        'subject' => $mail->msg->subject,
        'from_email' => $mail->msg->from_email,
        'from_name' => $mail->msg->from_name,
        'email' => $mail->msg->email,
        'to' => array(
                'email' => 'test@gmail.com',
                'name' => 'TO_NAME',
        'headers' => $headers,
         'headers' => $headers,

file_put_contents('filename.txt', print_r($message, true));

To Parse Reply Text use below code

If you want to get exact reply email use this code

$body_array = explode("\n",$mail->msg->text);
$fromName  = $mail->msg->from_name;
$fromEmail = $mail->msg->from_email;
$message = "";
foreach($body_array as $key => $value){
	//remove hotmail sig
	if($value == "_________________________________________________________________"){
	//original message quote
	} elseif(preg_match("/^-*(.*)Original Message(.*)-*/i",$value,$matches)){
	//check for date wrote string
	} elseif(preg_match("/^On(.*)wrote:(.*)/i",$value,$matches)) {
	//check for From Name email section
	} elseif(preg_match("/^On(.*)$fromName(.*)/i",$value,$matches)) {
	//check for To Name email section
	} elseif(preg_match("/^(.*)$fromEmail(.*)wrote:(.*)/i",$value,$matches)) {
	//check for quoted ">" section
	} elseif(preg_match("/^>(.*)/i",$value,$matches)){
	//check for date wrote string with dashes
	} elseif(preg_match("/^---(.*)On(.*)wrote:(.*)/i",$value,$matches)){
	//add line to body
	} else {
		$message .= "$value\n";


Thats all now you can read email and store email reply to your database

Hope it will help someone.

Marimuthu :