Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Craig Hopson

[SOLVED]piping emails to script

Recommended Posts

hi guys have this script to deal with the email it works great when you send from G-mail to script but ANYTHING else it does not handle the attachment and i just dont understand whats going on HELP!!!

#!/usr/bin/php -q<?php//  Use -q so that php doesn't print out the HTTP headers//  Anything printed to STDOUT will be sent back to the sender as an error!//  Config options$max_time_limit = 600; // in seconds// A safe place for files with trailing slash (malicious users could upload a php or executable file!)$save_directory = "/some/folder/path";$allowedSenders = Array('myemail@gmail.com',	'Bob the Builder <whatever@whoever.com>'); // only people you trust!$send_email = TRUE; // Send confirmation e-mail?$save_msg_to_db = TRUE; // Save e-mail body to DB?$db_host = 'localhost';$db_un = 'db_un';$db_pass = 'password';$db_name = 'db_name';// ------------------------------------------------------set_time_limit($max_time_limit);ini_set('max_execution_time',$max_time_limit);global $from, $subject, $boundary, $message, $save_path,$files_uploaded;$save_path = $save_directory;$files_uploaded = Array();function formatBytes(&$bytes, $precision = 2) {	$units = array('B', 'KB', 'MB', 'GB', 'TB');	$bytes = max($bytes, 0);	$pow = floor(($bytes ? log($bytes) : 0) / log(1024));	$pow = min($pow, count($units) - 1);	$bytes /= pow(1024, $pow);	return round($bytes, $precision) . ' ' . $units[$pow];}function process_part(&$email_part){	global $message;	// Max two parts. The data could have more than one \n\n in it somewhere,	// but the first \n\n should be after the content info block	$parts = explode("\n\n",$email_part,2);	$info = split("\n",$parts[0]);	$type;	$name;	$encoding;	foreach($info as $line){	if(preg_match("/Content-Type: (.*);/",$line,$matches)){		$type = $matches[1];	}	if(preg_match("/Content-Disposition: attachment; filename=\"(.*)\"/",		$line,$matches)){		$name = time() . "_" . $matches[1];	}	if(preg_match("/Content-Transfer-Encoding: (.*)/",$line,$matches)){		$encoding = $matches[1];	}	}	// We don't know what it is, so we don't know how to process it	if(!isset($type)){ return FALSE; }	switch($type){	case 'text/plain':	// "But if you get a text attachment, you're going to overwrite	// the real message!" Yes. I don't care in this case...	$message = $parts[1];	break;	case 'multipart/alternative':	// Multipart comes where the client sends the data in two formats so	// that recipients who can't read (or don't like) fancy content	// have another way to read it. Eg. When sending an html formatted	// message, they will also send a plain text message	process_multipart($info,$parts[1]);	break;	default:	if(isset($name)){ // the main message will not have a file name...		// text/html messages won't be saved!		process_data($name,$encoding,$parts[1]);	}elseif(!isset($message) && strpos($type,'text') !== FALSE){		$message = $parts[1]; // Going out on a limb here...capture		// the message	}	break;	}}function process_multipart(&$info,&$data){	global $message;	$bounds;	foreach($info as $line){	if (preg_match("/boundary=(.*)$/",$line,$matches)){		$bounds = $matches[1];	}	}	$multi_parts = split("--" .$bounds,$data);	for($i = 1;$i < count($multi_parts);$i++){	process_part($multi_parts[$i]);	}}function process_data(&$name,&$encoding = 'base64' ,&$data){	global $save_path,$files_uploaded;	// find a filename that's not in use. There's a race condition	// here which should be handled with flock or something instead	// of just checking for a free filename	$unlocked_and_unique = FALSE;	while(!$unlocked_and_unique){	// Find unique	$name = time() . "_" . $name;	while(file_exists($save_path . $name)) {		$name = time() . "_" . $name;	}	// Attempt to lock	$outfile = fopen($save_path.$name,'w');	if(flock($outfile,LOCK_EX)){		$unlocked_and_unique = TRUE;	}else{		flock($outfile,LOCK_UN);		fclose($outfile);	}	}	if($encoding == 'base64'){	fwrite($outfile,base64_decode($data));	}elseif($encoding == 'uuencode'){	// I haven't actually seen this in an e-mail, but older clients may	// still use it...not 100% sure that this will work correctly as is	fwrite($outfile,convert_uudecode($data));	}	flock($outfile,LOCK_UN);	fclose($outfile);	// This is for readability for the return e-mail and in the DB	$files_uploaded[$name] = formatBytes(filesize($save_path.$name));}// Process the e-mail from stdin$fd = fopen('php://stdin','r');$email = '';while(!feof($fd)){ $email .= fread($fd,1024); }// Headers hsould go till the first \n\n. Grab everything before that, then// split on \n and process each line$headers = split("\n",array_shift(explode("\n\n",$email,2)));foreach($headers as $line){	// The only 3 headers we care about...	if (preg_match("/^Subject: (.*)/", $line, $matches)) {	$subject = $matches[1];	}	if (preg_match("/^From: (.*)/", $line, $matches)) {	$from = $matches[1];	}	if (preg_match("/boundary=(.*)$/",$line,$matches)){	$boundary = $matches[1];	}}// Check $from here and exit if it's blank or// not someone you want to get mail from!if(!in_array($from,$allowedSenders)){	die("Not an allowed sender");}// No boundary was in the e-mail sent to us. We don't know what to do!if(!isset($boundary)){	die("I couldn't find an e-mail boundary. Maybe this isn't an e-mail");}// Split the e-mail on the found boundary// The first part will be the header (hence $i = 1 in our loop)// Each other chunk should have some info on the chunk,// then \n\n then the chunk data// Process each chunk$email_parts = split("--" . $boundary,$email);for($i = 1;$i < count($email_parts);$i++){	process_part($email_parts[$i]);}// Put the results in the database if neededif($save_msg_to_db){	mysql_connect($db_host,$db_un,$db_pass);	mysql_select_db($db_name);	$q = "INSERT INTO `emails` (`from`,`subject`,`body`) VALUES ('" .	mysql_real_escape_string($from) . "','" .	mysql_real_escape_string($subject) . "','" .	mysql_real_escape_string($message) . "')";	mysql_query($q) or die(mysql_error());	if(count($files_uploaded) > 0){	$id = mysql_insert_id();	$q = "INSERT INTO `files` (`email_id`,`filename`,`size`) VALUES ";	$filesar = Array();	foreach($files_uploaded as $f => $s){		$filesar[] = "('$id','" .		mysql_real_escape_string($f) . "','" .		mysql_real_escape_string($s) . "')";	}	$q .= implode(', ',$filesar);	mysql_query($q) or die(mysql_error());	}}// Send response e-mail if neededif($send_email && $from != ""){	$to = $from;	$newmsg = "Thanks! I just uploaded the following ";	$newmsg .= "files to your storage:\n\n";	$newmsg .= "Filename -- Size\n";	foreach($files_uploaded as $f => $s){	$newmsg .= "$f -- $s\n";	}	$newmsg .= "\nI hope everything looks right. If not,";	$newmsg .=  "please send me an e-mail!\n";	mail($to,$subject,$newmsg);}

THIS SCRIPT COME FROM HERE

Edited by Craig Hopson

Share this post


Link to post
Share on other sites

what have you tried as far a figuring out where it goes wrong?

Share this post


Link to post
Share on other sites

Nothing i cut and pasted the script i dont understand it i'm a newbi (well 2 years trying) i think it mabe something to do with base64 coding????? but i dont know

Share this post


Link to post
Share on other sites

You would need to add quite a bit of debugging to figure out what the issue is. You'll need to output all of the data that the script is working with so you can go through and compare the runs that work with the ones that don't to see why. I would output the entire email text, the text for each part, what it thinks the type, encoding, etc is for each part, and whatever else you think will be helpful for determine where the problem is.

Share this post


Link to post
Share on other sites

Hi all this is the final WORKING code

#!/usr/bin/php -q<?php//  Use -q so that php doesn't print out the HTTP headers/** mailReader.php** Recieve mail and attachments with PHP** Usage:* This script expects to recieve raw emails via STDIN.** Configure your mail server to pipe emails to this script. (See* http://stuporglue.org/add-an-email-address-that-forwards-to-a-script/* for instructions).  Make this script executable, and edit the* configuration options to suit your needs. Change permissions* of the directories so that the user executing the script (probably the* mail user) will have write permission to the file upload directory.** By default the script is configured to save pdf, zip, jpg, png and gif files.* Edit the switch statements around line 200 to change this.** Requirements:* You will need mimeDecode.php from http://pear.php.net/package/Mail_mimeDecode/* I used version 1.5.5** Copyright 2012, Michael Moore* Licensed under the same terms as PHP itself. You are free to use this script* for personal or commercial projects. Use at your own risk. No guarantees or* warranties.** Contact:* <stuporglue@gmail.com>* http://stuporglue.org** Support:* Limited free support available in the comments on the webpage for this script* or via email. Contracted support available for specific projects.* http://stuporglue.org/mailreader-php-parse-e-mail-and-save-attachments-php-version-2/** Thanks:* Many thanks to forahobby of www.360-hq.com for testing this script and helping me find* the initial bugs.* Thanks to Craig Hopson of twitterrooms.co.uk for help tracking down an iOS email handling bug.*/global $save_directory,$saved_files,$debug,$body;/***  Configuration Options**/// What's the max # of seconds to try to process an email?$max_time_limit = 600;// A safe place for files WITH TRAILING SLASH// Malicious users could upload a php or executable file,// so keep this out of your web root$save_directory = "/a/safe/save/directory/";// Allowed senders is now just the email part of the sender (no name part)$allowed_senders = Array(    'myemail@example.com',    'whatever@example.com',);// Send confirmation e-mail back to sender?$send_email = FALSE;// Save e-mail message and file list to DB?$save_msg_to_db = FALSE;// Configure your MySQL database connection here$db_host = 'localhost';$db_un = 'db_un';$db_pass = 'db_pass';$db_name = 'db_name';$debug = FALSE;/***  End of Configuration Options**///Anything printed to STDOUT will be sent back to the sender as an error!//error_reporting(-1);//ini_set("display_errors", 1);// Initialize the other global, set PHP options, load email library$saved_files = Array();set_time_limit($max_time_limit);ini_set('max_execution_time',$max_time_limit);require_once('mimeDecode.php');// Some functions we'll usefunction formatBytes($bytes, $precision = 2) {    $units = array('B', 'KB', 'MB', 'GB', 'TB');    $bytes = max($bytes, 0);    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));    $pow = min($pow, count($units) - 1);    $bytes /= pow(1024, $pow);    return round($bytes, $precision) . ' ' . $units[$pow];}// Find a happy place! Find a happy place!function saveFile($filename,$contents,$mimeType){    global $save_directory,$saved_files,$debug;    $filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);    $unlocked_and_unique = FALSE;    while(!$unlocked_and_unique){// Find unique$name = time() . "_" . $filename;while(file_exists($save_directory . $name)) {	 $name = time() . "_" . $filename;}// Attempt to lock$outfile = fopen($save_directory.$name,'w');if(flock($outfile,LOCK_EX)){	 $unlocked_and_unique = TRUE;}else{	 flock($outfile,LOCK_UN);	 fclose($outfile);}    }    fwrite($outfile,$contents);    fclose($outfile);    // This is for readability for the return e-mail and in the DB    $saved_files[$name] = Array('size' => formatBytes(filesize($save_directory.$name)),'mime' => $mimeType    );}function decodePart($body_part){    global $body,$debug;    if(array_key_exists('name',$body_part->ctype_parameters)){ // everyone else I've tried$filename = $body_part->ctype_parameters['name'];    }else if($body_part->d_parameters && array_key_exists('filename',$body_part->d_parameters)){ // hotmail$filename = $body_part->d_parameters['filename'];    }else{$filename = "file";    }    if($debug){print "Found body part type {$body_part->ctype_primary}/{$body_part->ctype_secondary}\n";    }    $mimeType = "{$body_part->ctype_primary}/{$body_part->ctype_secondary}";    switch($body_part->ctype_primary){    case 'text':switch($body_part->ctype_secondary){case 'plain':	 $body = $body_part->body; // If there are multiple text/plain parts, we will only get the last one.	 break;}break;    case 'application':switch ($body_part->ctype_secondary){case 'pdf': // save these file typescase 'zip':case 'octet-stream':	 saveFile($filename,$body_part->body,$mimeType);	 break;default:	 // anything else (exe, rar, etc.) will faill into this hole and die	 break;}break;    case 'image':switch($body_part->ctype_secondary){case 'jpeg': // Save these image typescase 'png':case 'gif':	 saveFile($filename,$body_part->body,$mimeType);	 break;default:	 break;}break;    case 'multipart':if(is_array($body_part->parts)){	 foreach($body_part->parts as $ix => $sub_part){  decodePart($sub_part);	 }}break;    default:// anything else isn't handledbreak;    }}//// Actual email handling starts here!//// Process the e-mail from stdin$fd = fopen('php://stdin','r');$raw = '';while(!feof($fd)){ $raw .= fread($fd,1024); }// Uncomment this for debugging.// Then you can do// cat /my/saved/file.raw | ./mailReader.php// for testing//file_put_contents("$save_directory/" . time() . "_email.raw",$raw);// Now decode it!// http://pear.php.net/manual/en/package.mail.mail-mimedecode.decode.php$decoder = new Mail_mimeDecode($raw);$decoded = $decoder->decode(    Array('decode_headers' => TRUE,'include_bodies' => TRUE,'decode_bodies' => TRUE,    ));// Set $from_email and check if it's allowed$from = $decoded->headers['from'];$from_email = preg_replace('/.*<(.*)>.*/',"$1",$from);if(!in_array($from_email,$allowed_senders)){    die("$from_email not an allowed sender");}// Set the $subject$subject = $decoded->headers['subject'];// Find the email body, and any attachments// $body_part->ctype_primary and $body_part->ctype_secondary make up the mime type eg. text/plain or text/htmlif(is_array($decoded->parts)){    foreach($decoded->parts as $idx => $body_part){decodePart($body_part);    }}// $from_email, $subject and $body should be set now. $saved_files should have// the files we captured// Put the results in the database if neededif($save_msg_to_db){    mysql_connect($db_host,$db_un,$db_pass);    mysql_select_db($db_name);    $q = "INSERT INTO `emails` (`from`,`subject`,`body`) VALUES ('" .mysql_real_escape_string($from_email) . "','" .mysql_real_escape_string($subject) . "','" .mysql_real_escape_string($body) . "')";    mysql_query($q) or die(mysql_error());    if(count($saved_files) > 0){$id = mysql_insert_id();$q = "INSERT INTO `files` (`email_id`,`filename`,`size`,`mime`) VALUES ";$filesar = Array();foreach($saved_files as $f => $data){	 $filesar[] = "('$id','" .  mysql_real_escape_string($f) . "','" .  mysql_real_escape_string($data['size']) . "','" .  mysql_real_escape_string($data['mime']) . "')";}$q .= implode(', ',$filesar);mysql_query($q) or die(mysql_error());    }}// Send response e-mail if neededif($send_email && $from_email != ""){    $to = $from_email;    $newmsg = "Thanks! I just uploaded the following ";    $newmsg .= "files to your storage:\n\n";    $newmsg .= "Filename -- Size\n";    foreach($saved_files as $f => $s){$newmsg .= "$f -- $s\n";    }    $newmsg .= "\nI hope everything looks right. If not,";    $newmsg .=  "please send me an e-mail!\n";    mail($to,$subject,$newmsg);}if($debug){    print "From : $from_email\n";    print "Subject : $subject\n";    print "Body : $body\n";    print "Saved Files : \n";    print_r($saved_files);}

for more info goto Stuporglue.org

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×