Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert incoming e-mail message into mySQL database? [closed]

Tags:

php

email

mysql

Just to say... I have no idea how would I do this :).

In other words, the thing is: You get a mail message from some guy [email protected], you make a reply with your own content, and [email protected] have your reply stored in his database.

Additional: I use shared hosting, I code in PHP, I understand ASP. If you have an idea how to write this script in another language, don't bother explaining me, because I won't understand anything.

A link to a solution is also welcomed.

Thanks in advance.

like image 547
pinky Avatar asked Aug 12 '10 14:08

pinky


People also ask

Is there an email datatype in mysql?

a varchar(50 ) would be enough for storing email..


1 Answers

So
- you have a server
- you get emails
- you want to save them int a mysql database

Cpanel config
- go to cpnal email forwarder
- add a new one
- redirect to PATH -> /home/your_user/whatever/php.script.php

Php script (you may need to change the "/usr/bin/php -q" path depending on your server configuration)

#!/usr/bin/php -q
<?php
chdir(dirname(__FILE__));
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
    $email .= fread($fd, 1024);
}
fclose($fd);

if(strlen($email)<1) {
    die(); 
}

// handle email
$lines = explode("\n", $email);

// empty vars
$from = "";
$to="";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;

for ($i=0; $i < count($lines); $i++) {
    if ($splittingheaders) {
        // this is a header
        $headers .= $lines[$i]."\n";
        // look out for special headers
        if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
            $subject = $matches[1];
        }
        if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
            $from = $matches[1];
        }
        if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
            $to = $matches[1];
        }
    } else {
        // not a header, but message
        $message .= $lines[$i]."\n";
    }
    if (trim($lines[$i])=="") {
        // empty line, header section has ended
        $splittingheaders = false;
    }
}

Works on shared hosting too! :)

All you need to add is the mysql insert and use the above-defined variables. Do you know how to use a mysql database from php? Or do you need help with that too?

like image 181
vlad b. Avatar answered Oct 12 '22 15:10

vlad b.