ich habe hier noch ein schönes kleines Script gefunden was den Pop3 Abfrägt und die Daten in eine Db speichert. Die Db musst Du dir aber selber erstellen.
Code: Alles auswählen
<html>
<head>
<style type="text/css">
<!--
.style {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
-->
</style>
</head>
<body>
<table width="100%" border="0" cellspacing="10" cellpadding="0">
<tr>
<td><span class="style">
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// ---------------------------------------------------------------------------- //
// Script config
$my_config = array(); // Configuration Parameters
$my_mail = array(); // Mail parameters for each mail looped
$my_master = array(); // Script master variables
$my_config['debug'] = TRUE;
$my_config['sendmail'] = FALSE; // Schickt Sie die Anzeige zu den gegebenen adress - > verwendet zu
$my_config['sendmail_to'] = '';
$my_config['display_content'] = FALSE; // !! Aktivieren Sie nicht, wenn Briefkasten eine Menge Anzeigen als er enthält
// verlangsamt hinunter den Prozeß ziemlich schwer
$my_config['delete_mail'] = TRUE; // Löschungpost vom Bediener nach analysieren
$my_config['move_mail'] = ''; // wenn anders als "", Post auf gegebenes Heft verschoben werden
$my_config['writetoDB'] = TRUE; // Speichern Sie Post in der SQL-Datenbank
$my_config['folder'] = 'inbox'; // Verwendet für SQL-Tabelle, Feld "folder"
$my_config['save_attachments'] = TRUE;
$my_config['send_invalidattach_mail'] = TRUE; // Wenn unzulässig, antworten die gefundenen Zubehöre, auf Absender
$my_config['sql']['host'] = "localhost";
$my_config['sql']['user'] = "web1";
$my_config['sql']['pass'] = "";
$my_config['sql']['db'] = "";
$my_config['IMAP']['host'] = "{localhost/pop3:110}";
$my_config['IMAP']['user'] = "web1p2";
$my_config['IMAP']['pass'] = "";
$my_config['IMAP']['folder'] = "INBOX";
// ---------------------------------------------------------------------------- //
// Connect to DB and IMAP
if (!@$dbh=mysql_connect ($my_config['sql']['host'], $my_config['sql']['user'], $my_config['sql']['pass'])) {
debug("mySQL connection failed");
exit;
} else {
mysql_select_db ($my_config['sql']['db'],$dbh);
$run_query = mysql_query("UPDATE runs SET last=NOW() WHERE id=1",$dbh);
debug("mySQL OK");
}
$imapconnect = $my_config['IMAP']['host'].$my_config['IMAP']['folder'];
if (!@$imapmailbox = imap_open ($imapconnect, $my_config['IMAP']['user'], $my_config['IMAP']['pass'])) {
debug("IMAP connection failed");
exit;
}
else { debug("IMAP OK"); }
// ---------------------------------------------------------------------------- //
// Number of messages
$imapcheck = imap_check($imapmailbox);
$my_master['Nmsgs'] = $imapcheck->Nmsgs;
debug(" ".$my_master['Nmsgs']." messages in $imapconnect<br><hr size="3" noshade>"); debug('');
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// Begin Mail Loop
$my_master['loopindex'] = 1;
$mailsdeleted=0;
while ($my_master['loopindex'] <= $my_master['Nmsgs']) {
debug("<br><b>Analyzing message nr. ".$my_master['loopindex']." <br>-------------------------------------------------<br></b>");
// ---------------------------------------------------------------------------- //
//get mail headers and structure
$header = imap_headerinfo($imapmailbox, $my_master['loopindex'],250,250);
$structure = imap_fetchstructure($imapmailbox, $my_master['loopindex']);
$my_mail['type'] = $structure->type; // Mail type (0=TEXT 1=MULTIPART)
$my_mail['tcode'] = $structure->encoding; // Mail encoding
// ---------------------------------------------------------------------------- //
//extract header information
$date = $header->udate; // -> UNIX TIMESTAMP
$my_mail['date'] = date("Y/m/d H:i",$date);
$from_email_mailbox = $header->from[0]->mailbox; // jack
$from_email_host = $header->from[0]->host; // something.com
$my_mail['from']['email'] = $from_email_mailbox."@".$from_email_host; // jack@something.com
$my_mail['from']['name'] = $header->from[0]->personal; // JACK SOMETHING
$to_email_mailbox = $header->to[0]->mailbox;
$to_email_host = $header->to[0]->host;
$my_mail['to']['email'] = $to_email_mailbox."@".$to_email_host;
$my_mail['to']['name'] = $header->to[0]->personal;
$replyto_email_mailbox = $header->reply_to[0]->mailbox;
$replyto_email_host = $header->reply_to[0]->host;
$my_mail['replyto']['email'] = $replyto_email_mailbox."@".$replyto_email_host;
$my_mail['replyto']['name'] = $header->reply_to[0]->personal;
$my_mail['cc'] = $header->ccaddress; // multiple CC's resp. BCC's possible
$my_mail['bcc'] = $header->bccaddress; // multiple CC's resp. BCC's possible
$my_mail ['subject'] = $header->fetchsubject;
// ---------------------------------------------------------------------------- //
// Decode header elements
$my_mail['from']['name'] = utf8_decode(imap_utf8($my_mail['from']['name']));
$my_mail['to']['name'] = utf8_decode(imap_utf8($my_mail['to']['name']));
$my_mail['replyto']['name'] = utf8_decode(imap_utf8($my_mail['replyto']['name']));
$my_mail['subject'] = utf8_decode(imap_utf8($my_mail['subject']));
$my_mail['subject'] = quoted_printable_decode($my_mail['subject']);
// ---------------------------------------------------------------------------- //
// Extract and decode mailtext & attachment(s)
// TYPE 0 MAIL (plain)
if ($my_mail['type'] == 0) {
// Get mail body
$mailtext = imap_body($imapmailbox, $my_master['loopindex']);
if ($my_mail['tcode'] == 3) {
$mailtext = base64_decode($mailtext);
} else {
$mailtext = quoted_printable_decode($mailtext);
}
$my_mail['body'] = $mailtext;
}
// TYPE 1 MAIL (multipart)
if ($my_mail['type'] == 1) {
$struct = $structure;
$mbox = $imapmailbox;
$mid = $my_master['loopindex'];
$parts = $struct->parts;
$i = 0;
$endwhile = false;
$stack = array(); // Stack while parsing message
$content = ""; // Message content
$my_mail['attachment'] = array(); // Attachments
while (!$endwhile) {
if (!$parts[$i]) {
if (count($stack) > 0) {
$parts = $stack[count($stack)-1]["p"];
$i = $stack[count($stack)-1]["i"] + 1;
array_pop($stack);
} else {
$endwhile = true;
}
}
if (!$endwhile) {
// Get message part (1.1.1 eg.)
$partstring = "";
foreach ($stack as $s) {
$partstring .= ($s["i"]+1) . ".";
}
$partstring .= ($i+1);
if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") { // Part is attachment
$my_mail['attachment'][] = array("filename" => $parts[$i]->parameters[0]->value,"filedata" => imap_fetchbody($mbox, $mid, $partstring));
} elseif (strtoupper($parts[$i]->subtype) == "PLAIN") { // Part is Message
$content .= imap_fetchbody($mbox, $mid, $partstring);
}
}
if ($parts[$i]->parts) {
$stack[] = array("p" => $parts, "i" => $i);
$parts = $parts[$i]->parts;
$i = 0;
} else {
$i++;
}
}
$my_mail['body'] = $content;
// ---------------------------------------------------------------------------- //
// extract and save attachments, if any
$my_mail['nbattachs'] = count($my_mail['attachment']);
if ($my_mail['nbattachs'] > 0) {
// attachments found
debug("Mail has ".$my_mail['nbattachs']." Attachments");
//Definieren Sie Zubehörschleifenfunktionen
$attach_invalid = 0;
$a = 0;
$str = "";
$dirname = "";
//create specific folders
$dirname = random();
$dirpath = "/home/www/web1/html/imap2sql/_attachments/".$dirname;
while(is_dir("$dirpath")) {
$dirname = random();
$dirpath = "_attachments/".$dirname;
}
if ($my_config['save_attachments']) {
mkdir("$dirpath", 0777);
debug("(Created folder => $dirname)");
} else {
debug("(Folder not created: save_attachments OFF)");
}
// schlingen Sie Zubehöre, decodieren Sie und speichern Sie sie
while ($a <= $my_mail['nbattachs']-1) {
$filename = "";
$filename = utf8_decode(imap_utf8($my_mail['attachment'][$a]['filename']));
//$filename = quoted_printable_decode($my_mail['attachment'][$a]['filename']);
debug("(".$a ." => ".$filename." | ",0);
// Überprüfen Sie, ob Zubehör gültig ist
if (!preg_match("=.jpg$|.gif$|.bmp$|.png$|.rar$|.zip$|.pdf$|.xls$|.doc$|.txt$|.htm$|.html$|.jpeg$=i",$filename)) {
// File Type is invalid
debug("INVALID)");
$attach_invalid++;
$attachs_error_echo.= $filename."*";
} else {
// Aktenart ist, fortfahren gültig
debug("VALID) ",0);
// decode content
if (preg_match("=.txt$=i",$filename)) {
$input = $my_mail['attachment'][$a]['filedata'];
} else {
$input = base64_decode($my_mail['attachment'][$a]['filedata']);
}
// save content
if ($my_config['save_attachments']) {
// check if filename exists in that directory and open handle
chmod ($dirpath, 0777) or die('Konnte die Rechte nicht ändern von: <BR><i>' . $dirpath . '</i>') ;
$handle = fopen($dirpath."/".$filename, "w") or die('Konnte die Datei: <BR><i>' . $filename . '</i> nicht anlegen!');
//if (fwrite($handle, $input)) {
// debug("Saved => ".$filename);
//} else {
// debug("Save => ".$filename." failed!");
//}
if (!fwrite($handle, $input)) {
print "Kann in die Datei $filename nicht schreiben";
exit;
}
fclose($handle);
} else {
debug("save_attachments OFF");
}
}
$a++;
}
// One or more Attachments were invalid
if ($attach_invalid == $my_mail['nbattachs']) {
// None of the attach(s) valid -> delete folder
@rmdir($dirpath);
debug ("NONE OF THE ATTACH(S) VALID -> $dirpath DELETED");
unset($dirpath, $dirname);
}
if($attachs_error_echo){ // -> send notification mail to sender
$new_subject = "Re: ".$my_mail['subject'];
$new_body = "Note that this is an automated message\n\n\nWe have received your email. However, one or more attachments were not accepted, since they violated the systems security issues:\n\n$attachs_error_echo\n\nWith * marked files we had to decline.\n\n\n";
if ($my_config['send_invalidattach_mail']) {
mail($my_mail['from']['email'],$new_subject,$new_body,"From: YOURNAME <box@host.com>\nReply-To: YOURNAME <box@host.com>");
$insertDB = mysql_query("INSERT INTO `email` ( `id` , `date` , `type` , `encoding` , `folder` , `from_name` , `from_mail` , `to_name` , `to_mail` , `replyto_name` , `replyto_mail` , `subj` , `text` , `cc` , `dir` ) VALUES ('' , 'NOW()' , '0' , '0' , 'sent' , 'YOURNAME' , 'box@host.com' , '".$my_mail['from']['name']."' , '".$my_mail['from']['email']."' , '".$my_mail['from']['name']."' , '".$my_mail['from']['email']."' , '".$new_subject."' , '".$new_body."' , '' , '0')",$dbh);
debug ("INVALID ATTACH(S) MAIL SENT TO ".$my_mail['from']['email']."");
} else {
debug("Send invalid_attach_mail OFF");
}
}
} else {
// no attachments found in email
debug("No attachments were found");
}
// decode mailtext
$my_mail['body'] = quoted_printable_decode($my_mail['body']);
//$my_mail['body'] = base64_decode($my_mail['body']);
}
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// do corrections -> cleaning up a little
// from
if ($my_mail['from']['name'] == "") {
$my_mail['from']['name'] = $my_mail['from']['email'];
}
$my_mail['from']['name'] = ereg_replace("'","",$my_mail['from']['name']);
$my_mail['from']['name'] = ereg_replace(""","",$my_mail['from']['name']);
$my_mail['from']['name'] = addslashes($my_mail['from']['name']);
// To
if ($my_mail['to']['name'] == "") {
$my_mail['to']['name'] = $my_mail['to']['email'];
}
$my_mail['to']['name'] = ereg_replace("'","",$my_mail['to']['name']);
$my_mail['to']['name'] = ereg_replace(""","",$my_mail['to']['name']);
$my_mail['to']['name'] = addslashes($my_mail['to']['name']);
// reply to
if ($my_mail['replyto']['name'] == "") {
$my_mail['replyto']['name'] = $my_mail['from']['name'];
}
if ($my_mail['replyto']['email'] == "") {
$my_mail['replyto']['email'] = $my_mail['from']['email'];
}
$my_mail['replyto']['name'] = ereg_replace("'","",$my_mail['replyto']['name']);
$my_mail['replyto']['name'] = ereg_replace(""","",$my_mail['replyto']['name']);
$my_mail['replyto']['name'] = addslashes($my_mail['replyto']['name']);
$my_mail['cc'] = ereg_replace("'","",$my_mail['cc']);
$my_mail['cc'] = ereg_replace(""","",$my_mail['cc']);
$my_mail['cc'] = addslashes($my_mail['cc']);
$my_mail['bcc'] = ereg_replace("'","",$my_mail['bcc']);
$my_mail['bcc'] = ereg_replace(""","",$my_mail['bcc']);
$my_mail['bcc'] = addslashes($my_mail['bcc']);
$my_mail['subject'] = addslashes($my_mail['subject']);
$my_mail['body'] = strip_tags($my_mail['body']);
$my_mail['body'] = addslashes($my_mail['body']);
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// OUTPUT DEBUG
//print mailinfo (debug only)
debug("<br>",0);
debug("Type: ".$my_mail['type']."");
debug("Encoding: ".$my_mail['tcode']."");
debug("HEADER Date: ".$my_mail['date']."");
debug("HEADER From: ".$my_mail['from']['name']." [".$my_mail['from']['email']."]");
debug("HEADER To: ".$my_mail['to']['name']." [".$my_mail['to']['email']."]");
debug("HEADER ReplyTo: ".$my_mail['replyto']['name']." [".$my_mail['replyto']['email']."]");
debug("HEADER CC: ".$my_mail['cc']."");
debug("HEADER BCC: ".$my_mail['bcc']."");
debug("");
debug("HEADER Subject: ".$my_mail['subject']."");
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// Some output and action based on triggers
if ($my_config['display_content']) {
debug("<hr size="1" noshade>>>>>>>>>> BODY <<<<<<<<<br><pre>".$my_mail['body']."</pre> <br><hr size="1" noshade>");
}
// send email
if ($my_config['sendmail']) {
if ($sendmailr = mail($my_config['sendmail'],$my_master['loopindex'],$my_mail['body'])) {
debug("Mail sent successfully");
} else {
debug("Send mail failed");
}
} else {
debug("Send mail turned OFF");
}
// move mail to an other IMAP folder
if ($my_config['move_mail'] != "") {
if ($move_mailr = imap_mail_move($imapmailbox,$my_master['loopindex'],$my_config['move_mail'])) {
debug("Mail successfully moved to ".$imaphost.$my_config['move_mail']."");
} else {
debug("Mail could not be moved to ".$imaphost.$my_config['move_mail']."");
}
} else {
debug("Move Mail turned OFF");
}
// Mark mail for deletion, exept if moved
if ($my_config['delete_mail'] && $my_config['move_mail'] == "") {
if ($delete_mailr = imap_delete($imapmailbox,$my_master['loopindex'])) {
debug("Mail successfully marked for deletion");
$mailsdeleted++;
} else {
debug("Mail could not be marked for deletion");
}
} else {
debug ("Mark Mail for deletion OFF");
}
// ---------------------------------------------------------------------------- //
// Insert mail to Database
if (!isset($dirname)) {
$dirname = 0;
}
// INSERT MAIL TO SQL
$my_mail['body'] = mysql_real_escape_string($my_mail['body'],$dbh);
$sql = "INSERT INTO `email` (
`id` ,
`date` ,
`type` ,
`encoding` ,
`folder` ,
`from_name` ,
`from_mail` ,
`to_name` ,
`to_mail` ,
`subj` ,
`text` ,
`cc` ,
`dir` ) VALUES (
'',
'".$my_mail['date']."',
'".$my_mail['type']."',
'".$my_mail['tcode']."',
'".$my_config['folder']."',
'".$my_mail['from']['name']."',
'".$my_mail['from']['email']."',
'".$my_mail['to']['name']."',
'".$my_mail['to']['email']."',
'".$my_mail['subject']."',
'".$my_mail['body']."',
'".$my_mail['cc']."',
'".$dirname."');";
//$sql = "INSERT INTO `email` ( `id` , `date` , `type` , `encoding` , `folder` , `answer` , `from_name` , `from_mail` , `to_name` , `to_mail` , `replyto_name` , `replyto_mail` , `subj` , `text` , `cc` , `dir`, ) VALUES ('' , '".$my_mail['date']."' , '".$my_mail['type']."' , '".$my_mail['tcode']."' , '".$my_config['folder']."' , '".$my_mail['from']['name']."' , '".$my_mail['from']['email']."' , '".$my_mail['to']['name']."' , '".$my_mail['to']['email']."' , '".$my_mail['replyto']['name']."' , '".$my_mail['replyto']['email']."' , '".$my_mail['subject']."' , '".$my_mail['body']."' , '".$my_mail['cc']."' , '$dirname')";
if ($my_config['writetoDB']) {
if ($result = mysql_query($sql,$dbh) or die(mysql_error() . '<BR><i>' . $sql . '</i>')) {
debug("Saved Mail to Database");
} else {
debug("Save Mail to Database failed! ---> ",0);
//debug(mysql_error());
}
} else {
debug("Save mail to database OFF");
}
debug("<br><br>---------------------eof-------------------------<br><br><hr size="3" noshade><br>");
$my_master['loopindex']++;
// ---------------------------------------------------------------------------- //
// Unset some variables before looping to next mail
unset($attachs_error_echo, $dirname, $dirpath, $my_mail);
}
// END LOOP => NEXT MAIL
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------- //
// Display final debug information and close IMAP/mySQL
debug("<br><br><hr size="3" noshade>");
// delete mails marked for deletion
if ($expunge_mails = imap_expunge($imapmailbox)) {
debug("Mails marked for deletion successfully deleted from server -> ".$mailsdeleted." Mails");
} else {
debug("Mails marked for deletion (".$mailsdeleted.") could not be deleted from server");
}
// close IMAP
if ($imap_close = imap_close($imapmailbox)) {
debug("Closed connection to IMAP Server successfully");
} else {
debug("Closing IMAP connection failed!");
}
// close mySQL
if ($mysql_close = mysql_close($dbh)) {
debug ("Closed connection to mySQL Server successfully");
} else {
debug("Closing mySQL connection failed!");
}
// ---------------------------------------------------------------------------- //
// DEBUG Function
function debug($output,$nobrake=TRUE) {
global $my_config;
if ($my_config['debug']) {
echo $output;
if ($nobrake) {
echo "<br>";
}
return TRUE;
}
}
// RANDOM FOLDER NAME
function random($length=16) {
$seeds = 'abcdefghijklmnopqrstuvwxyz123456789';
$seeds_count = strlen($seeds);
// Seed
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
// Generate
for ($i = 0; $length > $i; $i++) {
$str .= $seeds{mt_rand(0, $seeds_count - 1)};
}
return $str;
}
// ---------------------------------------------------------------------------- //
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 6);
debug ("Execution time: $total_time s");
?>
</span></td>
</tr>
</table>
</body>
</html>