Hjælp til mail 2 mysql script
Hej Exp'erHar fundet et script på nettet som henter mine emails og lægger dem i en mysql database.
Det virker men har et problem med at hvis en mail har flere modtager i til feltet så indsætter den første email adresse i listen af modtager som modtager adresse og ikke eksempelvis adresse nr 4 som er min email.
Er der en som kan hjælpe så den indsætter den rette til adresse i mysql ?
her er de 3 filer og sql filen:
PHPmail2system.functions.lib.php
-------
<?
/*
--------------------------------------------------------------------------------
| This file is part of PHPMail2System. |
| |
| PHPMail2System is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| Foobar is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with Foobar; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| |
| © 2003 Kevin Steffer |
| php-dev(at)linuxscope(dot)net |
| Any further development with this source is appreciated! |
| |
| ---------------- |
| Files within this distribution of PHPMail2MySQL |
| 1) PHPmail2system.php |
| 2) PHPmail2system.conf |
| 3) PHPmail2system.functions.lib |
| 4) PHPmail2system.sql |
| 5) COPYING.txt |
| 6) README.txt |
| |
| ---------------- |
| I will specially thank the people and the visitors at www.php.net for a |
| great work making it possible to have access to all the documentation and |
| NOT to forget all the users comments were a GOLD MINE to me! |
| |
| ---------------- |
| PHPmail2System is dedicated to Hans-Jörg Nolden @ www.noldenedv.de who |
| asked me to write this script and it made me have an excuse to sit |
| programming :) Thanks! |
--------------------------------------------------------------------------------
*/
/*
FUNCTION TO TRANSFORM ISOCODE TO UNICODE CHARACTERS // THE FUNCTION IS NOT FINISHED
*/
function transformstr($str) {
$str = ereg_replace("\=\?iso-8859-1\?Q\?","",$str);
$str = ereg_replace("\=\?ISO-8859-1\?Q\?","",$str);
$str = ereg_replace("\=E5","å",$str); // Replace to å
$str = ereg_replace("\=E6","æ",$str); // Replace to æ
$str = ereg_replace("\=F8","ø",$str); // Replace to ø
$str = ereg_replace("\?\=","",$str);
$str = ereg_replace("_"," ",$str);
$str = ereg_replace("\=3F","?",$str);
$str = ereg_replace("\=2E",".",$str);
$str = ereg_replace("\=2C",",",$str);
$str = ereg_replace("ø","ø",$str);
$str = ereg_replace("Ã¥","å",$str);
return $str;
}
/*
function transformHTML($str) {
if ((strpos($str,"<HTML") 0) || (strpos($str,"html") 0)) {
$makeHeader = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
if ((strpos($str,"<BODY") 0) || (strpos($str,"body") 0)) {
$makeBody = "\n<body>\n";
$str = $makeHeader . $makeBody . $str ."\n/body></html>";
} else {
$str = $makeHeader . $str ."\n</html>";
}
} else {
$str = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n". $str;
if (strpos($str,cid) != 0) {
$str = ereg_replace("<IMG id=ridImg"," ",$str);
$str = ereg_replace("src=\"cid:[0-9a-zA-Z$]+\@+[a-zA-Z$]+\" align=+[A-Za-z]+>","",$str);
}
}
return $str;
}
*/
/*
FUNCTION TO STORE THE FILE ON THE SERVER
*/
function storeFile($strFileType,$strFileName,$fileContent,$fileSize,$strFolder,$storagePolicy,$placeOnFS) {
/*
DETERMINE FILETYPE FROM EXTENSION
*/
$file2 = file('/etc/httpd/conf/apache-mime.types');
foreach($file2 as $line) {
rtrim($line);
if (preg_match('/^\#/', $line))
continue;
$elms = preg_split('/\s+/', $line);
$type = array_shift($elms);
foreach ($elms as $elm) {
$mime[$elm] = $type;
}
}
if (strpos($strFileType,".") <> 0) {
$strFileType = ereg_replace(".","",$strFileType);
$ContentType = $mime[$strFileType];
} else {
$ContentType = $mime[$strFileType];
}
// STORAGE POLICY SET TO 1
if ($storagePolicy == 1) {
$strFileName = $placeOnFS ."/". $strFolder ."/". $strFileName;
$strFilePath = $placeOnFS ."/". $strFolder ."/";
$strFolderOnFS = $placeOnFS ."/". $strFolder;
}
// STORAGE POLICY SET TO 0
if ($storagePolicy == 0) {
$strFileName = $placeOnFS ."/". $strFileName;
$strFilePath = $placeOnFS ."/";
}
$binfile = false;
if (substr($ContentType,0,4) == "text") {
$contentToWrite = imap_base64($fileContent);
$binfile = false;
} else {
$contentToWrite = imap_base64($fileContent);
$binfile = true;
}
/*
CHECK THAT THE DIR EXISTS IF NOT CREATE IT
*/
if($storagePolicy == 1 && !file_exists($strFolderOnFS) && !is_file($strFolderOnFS) && !is_dir($strFolderOnFS) ){
mkdir($strFolderOnFS,0755);
}
if (!file_exists($strFileName)) {
touch($strFileName); // Create blank file
chmod($strFileName,0666);
} else {
for ($n=1;$n<=100;$n++) {
if ($n < 2) {
if (substr($strFileType,0,1) == ".") {
$strFileName = ereg_replace($strFileType,"",$strFileName) ."_". $n . $strFileType;
} else {
$strFileName = ereg_replace(".".$strFileType,"",$strFileName) ."_". $n .".". $strFileType;
}
} else {
if (substr($strFileType,0,1) == ".") {
$strFileName = ereg_replace($strFileType,"",$strFileName) ."_". $n . $strFileType;
} else {
$strFileName = ereg_replace(".".$strFileType,"",$strFileName) ."_". $n .".". $strFileType;
}
$strFileName = ereg_replace("_".($n-1),"",$strFileName);
}
if (!file_exists($strFileName)) {
touch($strFileName); // Create blank file
chmod($strFileName,0666);
break;
}
}
}
$somecontent = $contentToWrite;
/*
CHECK THAT THE FILE EXISTS
*/
if (is_writable($strFileName)) {
/*
TRY TO OPEN THE FILE
*/
if (!$handle = fopen($strFileName, 'a+')) {
// print "Cannot open file ($strFileName)"; // FOR DEBUG PURPOSE
}
/*
TRY TO WRITE THE CONTENT TO THE FILE
*/
if ($binfile == false) {
if (!fwrite($handle, $somecontent)) {
// print "Cannot write file ($strFileName)\n"; // FOR DEBUG PURPOSE
//print "Success, wrote file ($strFileName)"; // FOR DEBUG PURPOSE
} else {
// echo "Wrote a TXT file\n";
}
} else {
if (!fputs($handle,$somecontent,$fileSize)) {
// print "Cannot write file ($strFileName)\n"; // FOR DEBUG PURPOSE
} else {
// echo "Wrote bin file\n";
}
}
/*
CLOSE THE FILE
*/
fclose($handle);
}
$strFileName = ereg_replace($strFilePath,"",$strFileName);
return $strFileName;
}
function getMonthInt($month) {
switch ($month) {
case "Jan":
$month = "01";
break;
case "Feb":
$month = "02";
break;
case "Mar":
$month = "03";
break;
case "Apr":
$month = "04";
break;
case "Mai":
$month = "05";
break;
case "Jun":
$month = "06";
break;
case "Jul":
$month = "07";
break;
case "Aug":
$month = "08";
break;
case "Sep":
$month = "09";
break;
case "Oct":
$month = "10";
break;
case "Nov":
$month = "11";
break;
case "Dec":
$month = "12";
break;
}
return $month;
}
function get_mime_type(&$structure) {
$primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
if($structure->subtype) {
return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
}
return "TEXT/PLAIN";
}
function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number = false) {
if(!$structure) {
$structure = imap_fetchstructure($stream, $msg_number);
}
if($structure) {
if($mime_type == get_mime_type($structure)) {
if(!$part_number) {
$part_number = "1";
}
$text = imap_fetchbody($stream, $msg_number, $part_number);
if($structure->encoding == 3) {
return imap_base64($text);
} else if($structure->encoding == 4) {
return imap_qprint($text);
} else {
return $text;
}
}
if($structure->type == 1) /* multipart */ {
while(list($index, $sub_structure) = each($structure->parts)) {
if($part_number) {
$prefix = $part_number . '.';
}
$data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix . ($index+1));
if($data) {
return $data;
}
}
}
}
return false;
}
?>
---------
PHPmail2system.conf.php
---------
<?
/*
CONFIGURE MAILBOX LOGIN
*/
$Mail_ServerName_conf = "mail.nfl-club.dk"; // NAME ON THE MAIL SERVER
$Mail_ServerAccessProtocol_conf = "imap"; // CAN BE imap or pop
$Mail_ServerAccessPort_conf = 143; // CAN WHAT YOU'VE SET MAILSERVER TO (default is pop=110 or imap=143
$Mail_UserName_conf = "brugernavn"; // USERNAME ON THE MAILSERVER FOR THE ACCOUNT TO RECEIVE FROM
$Mail_PassWord_conf = "kodeord"; // PASSWORD ON THE MAILSERVER FOR THE ACCOUNT TO RECEIVE FROM
/*
CONFIGURE WHERE TO STORE ATTACHMENTS ON THE FILESYSTEM
*/
$placeOnFS_conf = "/files";
/*
STORAGE POLICY IS AN OPTION WHERE YOU CAN CHOOSE BETWEEN
0) Storing all attachments in one and the same folder
For example /var/www/mysite/attachments (e.g. $placeOnFS_conf)
1) Storing files in a folder named after the date of the email that is received
For example /var/www/mysite/attachments/2003-31-12 (e.g. $placeOnFS_conf ."/". $msgDate)
Where the date is the date where of the email
NOT THE DATE WHEN YOU CHOOSE TO DOWNLOAD THE EMAIL FROM YOUR MAILBOX
This option is very important when you code your mail client so you can HARDCODE where
to look for the attachment files.
*/
$storagePolicy_conf = 1;
/*
ERROR REPORTING OPTION
1 = ON
0 = OFF
Don't forget to set $errorReportingEmail to your email address if it's ON
*/
$errorReporting_conf = 1;
$errorReportingEmail_conf = "fejl@nfl-club.dk";
/*
MySQL CONFIGURATION
$strMySQL_conf is the QUERYSTRING that should INSERT a row into a table.
Variables to deal with are:
$mail_recipient_address
$mail_sender_address
$mail_sender_name
$mail_dato
$mail_subject
$mail_body
$fileNames
($mail_attachmentsArray)
The variable $fileNames is a string containing all the filenames of the
attachments that were saved on the FS.
If you choose to save your attachment-filenames into a seperate table set
the option $MySQL_Normalized to 1
*/
$MySQL_ServerName_conf = "localhost";
$MySQL_UserName_conf = "brugernavn";
$MySQL_PassWord_conf = "kodeord";
$MySQL_DataBase_conf = "database";
// QUERYSTRING FOR NON NORMALIZED TABLE STRUCTURE
$MySQL_Normalized_conf = 1;
// QUERYSTRINGS FOR NORMALIZED TABLE STRUCTURE
/*
FUNCTION TO STORE THE MAIL
*/
function saveTheMail($fromemailadresse,$fromName,$toadr,$subj,$from,$dato,$fileNameArray,$msgBody,$MySQL_ServerName,$MySQL_UserName,$MySQL_PassWord,$MySQL_DataBase,$MySQL_Normalized) {
/*
VARIABLES TO STORE
*/
$mail_sender_address = $fromemailadresse;
$mail_sender_name = $fromName;
$mail_recipient_address = $toadr;
$mail_subject = $subj;
$mail_from = $from;
$mail_dato = $dato;
$mail_attachmentsArray = $fileNameArray;
$mail_body = $msgBody;
$fileNames = "";
for($o=0;$o<sizeof($mail_attachmentsArray);$o++) {
$fileNames .= $mail_attachmentsArray[$o] ."\n";
}
$dbcon = mysql_pconnect("$MySQL_ServerName","$MySQL_UserName","$MySQL_PassWord");
mysql_select_db("$MySQL_DataBase");
if ($MySQL_Normalized == 1) {
mysql_query("INSERT INTO mails (
toaddress,
fromaddress,
fromname,
dato,
subject,
body
)
VALUES(
'$mail_recipient_address',
'$mail_sender_address',
'$mail_sender_name',
'$mail_dato',
'$mail_subject',
'$mail_body'
)",$dbcon);
$returnQuery = mysql_query("SELECT MAX(id) FROM mails",$dbcon);
$rs = mysql_fetch_array($returnQuery);
$mail_message_indentity = $rs[0];
for($fileNumber=0;$fileNumber<sizeof($mail_attachmentsArray);$fileNumber++) {
mysql_query("INSERT INTO mail_attachments (
mailID,
filename
)
VALUES(
$mail_message_indentity,
'$mail_attachmentsArray[$fileNumber]'
)",$dbcon);
}
} else {
mysql_query("INSERT INTO mails (
toaddress,
fromaddress,
modtager,
password,
fromname,
dato,
subject,
body,
attachments
)
VALUES(
'$mail_recipient_address',
'$mail_sender_address',
'$mail_modtager',
'$mail_unikpass',
'$mail_sender_name',
'$mail_dato',
'$mail_subject',
'$mail_body',
'$fileNames'
)",$dbcon);
}
mysql_close($dbcon);
return true;
}
?>
----------
mail2sql.php
----------
<?
include("./PHPmail2system.conf.php");
include("./PHPmail2system.functions.lib.php");
$ServerName = "{". $Mail_ServerName_conf ."/". $Mail_ServerAccessProtocol_conf .":". $Mail_ServerAccessPort_conf ."}INBOX";
$UserName = $Mail_UserName_conf;
$PassWord = $Mail_PassWord_conf;
/*
OPENING MAILBOX
*/
$mbox = imap_open($ServerName, $UserName,$PassWord) or die("Could not open imap Mailbox - try again later!");
if ($hdr = imap_check($mbox)) {
// echo "Num Messages " . $hdr->Nmsgs ."\n\n<br><br>";
$msgCount = $hdr->Nmsgs;
} else {
echo "failed";
}
$MN=$msgCount;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
/*
START LOOPING THROUGH ALL THE MESSAGES
*/
for($ss=$size-1;$ss>=0;$ss--){
/*
GET HEADER DATA
*/
$val=$overview[$ss];
$msgno=$val->msgno;
$from=$val->from;
$dato=$val->date;
$subj=$val->subject;
$toadr=$val->to;
$hdrinfo = imap_headerinfo($mbox,$msgno,1024,"localhost");
$toadr = $hdrinfo->to[0]->mailbox ."@". $hdrinfo->to[0]->host;
/*
TRANSFORM NON ANSI CHARACTERS IN SUBJECT AND SENDER_INFO ($from)
*/
$from = ereg_replace("\"","",$from);
$subj = transformstr(imap_utf8($subj));
$from = transformstr(imap_utf8($from));
/*
FORMAT DATE DISPLAY INTO DANISH FORMAT (e.g. dd mm yyyy hh:mm:ss)
*/
list($dayName,$day,$month,$year,$time,$timezone) = split(" ",$dato);
$dato = $year ."-". getMonthInt($month) ."-". $day ." ". $time;
$dateFolder = $year ."-". getMonthInt($month) ."-". $day;
/*
SPLIT SENDER_INFO ($from) INTO "NAME <EMAIL>" FORMAT
*/
list($fromName,$fromemailadresse) = split(" <",$from);
$fromemailadresse = ereg_replace(">","",$fromemailadresse);
/* ATTACHMENT HANDLING */
$struct = imap_fetchstructure($mbox,$msgno);
$contentParts = count($struct->parts);
if ($contentParts >= 2) {
$filecounter = 0;
for ($i=2;$i<=$contentParts;$i++) {
$att[$i-2] = imap_bodystruct($mbox,$msgno,$i);
}
for ($k=0;$k<sizeof($att);$k++) {
if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") {
if ($att[$k]->parameters[1]->value != "") {
$strFileName = $att[$k]->parameters[0]->value;
$fileSize = $att[$k]->bytes;
$strFileType = strrev(substr(strrev($strFileName),0,4));
$fileContent = imap_fetchbody($mbox,$msgno,$k+2);
/*
CALL FUNCTION TO STORE THE FILE
*/
$fileNameToStore = storeFile($strFileType,$strFileName,$fileContent,$fileSize,$dateFolder,$storagePolicy_conf,$placeOnFS_conf);
/*
STORE THE FILENAME IN ARRAY
*/
$fileNameArray[$filecounter] = $fileNameToStore;
}
} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") {
$strFileName = $att[$k]->parameters[0]->value;
$fileSize = $att[$k]->bytes;
$strFileType = strrev(substr(strrev($strFileName),0,4));
$fileContent = imap_fetchbody($mbox,$msgno,$k+2);
/*
CALL FUNCTION TO STORE THE FILE
*/
$fileNameToStore = storeFile($strFileType,$strFileName,$fileContent,$fileSize,$dateFolder,$storagePolicy_conf,$placeOnFS_conf);
/*
STORE THE FILENAME IN ARRAY
*/
$fileNameArray[$filecounter] = $fileNameToStore;
}
$filecounter++;
}
}
/* END OF ATTACHMENT HANDLING */
/*
GET THE MESSAGE BODY
*/
// get plain text
$dataTxt = get_part($mbox, $msgno, "TEXT/PLAIN");
// get HTML text
$dataHtml = get_part($mbox, $msgno, "TEXT/HTML");
if ($dataHtml != "") {
// $msgBody = transformHTML($dataHtml);
$msgBody = $dataHtml;
} else {
$msgBody = ereg_replace("\n","<br>",$dataTxt);
$msgBody = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i","$1http://$2", $msgBody); //make sure there is an http:// on all URLs
$msgBody = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<A TARGET=\"_blank\" HREF=\"$1\">$1</A>", $msgBody); //make all URLs links
$msgBody = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A HREF=\"mailto:$1\">$1</A>",$msgBody);
}
if (saveTheMail($fromemailadresse,$fromName,$toadr,$subj,$from,$dato,$fileNameArray,$msgBody,$MySQL_ServerName_conf,$MySQL_UserName_conf,$MySQL_PassWord_conf,$MySQL_DataBase_conf,$MySQL_Normalized_conf)) {
imap_delete($mbox,$msgno);
imap_expunge($mbox);
} else {
if ($errorReporting_conf == 1 && strlen($errorReportingEmail_conf) > 5) {
mail($errorReportingEmail,"Error - storing mail","The Email from\n$fromName $fromemailadresse\nCould not be stored in MySQL\n\nThe mail is still in the mailbox on the server.");
}
}
unset($fileNameArray);
unset($mail_attachmentsArray);
unset($att);
}
/*
CLOSE THE MAILBOX
*/
imap_close($mbox);
?>
-------------
sqlfil.sql
-------------
CREATE TABLE `mails` (
`id` int(10) NOT NULL auto_increment,
`toaddress` varchar(250) NOT NULL default '',
`fromaddress` varchar(250) NOT NULL default '',
`fromname` varchar(250) default '0',
`dato` datetime NOT NULL default '0000-00-00 00:00:00',
`modtager` int(10) NOT NULL,
`password` text NOT NULL,
`subject` varchar(11) default 'email',
`body` text,
`attachments` varchar(250) default '0',
PRIMARY KEY (`id`),
KEY `Search` (`subject`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=40 ;