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~
IanArcher

Get Contents From E-Mail And Write It To Mysql Table

Recommended Posts

If you get the contents of the email then you can run a regular expression to look for any pattern you want, including URLs. I don't know what you mean "tweaked for SMS", SMS messages typically do not go to an email address, I believe those are MMS messages, and they would arrive in the same format as any other email.

Share this post


Link to post
Share on other sites

Thanks for replying.by tweaking I mean adjusting the code to work for sms, that is to make the script scan through sms or mms to pick contents/urls and push to database.

Share this post


Link to post
Share on other sites

That particular code works with an email server, not a server for SMS or MMS. I haven't researched what those servers use, maybe the use IMAP to log in, or maybe it's something else.

Share this post


Link to post
Share on other sites

Well, I haven't read through this thread in over 2 years, but I imagine there's a pretty decent amount of explanation already here. You can look up the PHP functions in the manual if you want specific information about what they do. Otherwise, if you have questions about code it's probably best to start a new topic and post the code you're currently using.

Share this post


Link to post
Share on other sites

Thanks very much @justsomeguy this post explains exactly what I want to do. However when i pasted in the full example script it seemed to be an invalid file (HTTP error 500).

I had filled in the imap login details correctly. 

What else would I need to do to make it work, are there any other variable names I should fill in in the script or anything?

Thanks Lyndon

Share this post


Link to post
Share on other sites

I'm not sure which of that code you're using, but it looks like at some point over the past 5 years or so a forum update removed the line breaks from code examples.  If you add the line breaks back to the code I assume it will work.  If the code contains any single-line comment it will comment out the rest of the code and that's probably the reason for a syntax error.

Share this post


Link to post
Share on other sites

I was using your example script from page 1 of this, that you had said "I'll do this when I get home". 

Yes I agree about the line breaks. I have tried adding them in hopefully the correct places but still the same error. I've posted the code here with line breaks re-added. 

Would you mind please either checking this below, or else re-posting your original one please? Thank you

<?php
$now = time(); 
// current time
$mailbox = '{your-mailserver-here/imap/novalidate-cert}INBOX'; 
// see http://www.php.net/manual/en/function.imap-open.php 
$mbox = imap_open($mailbox, 'email-address-here', 'password-here'); 
// log in to mail server
if (!$mbox)  echo ('Failed opening mailbox<br>' . print_r(imap_errors(), true)); 
// remove the print_r for production use
else{  $box = imap_check($mbox); 
	 // get the inbox  
	 for ($imap_idx = 1; $imap_idx <= $box->Nmsgs; $imap_idx++) 
	 // loop through the messages  
	 {    $headers = imap_headerinfo($mbox, $imap_idx); 
	  // http://www.php.net/manual/en/function.imap-headerinfo.php    
	  $raw_headers = imap_fetchheader($mbox, $imap_idx); 
	  // http://www.php.net/manual/en/function.imap-fetchheader.php    
	  $selected_headers = '';    $text_part = '';    $html_part = '';    
	  $original_message = imap_body($mbox, $imap_idx); 
	  // save the copy of the entire thing, attachments and all    
	  // build selected headers string    
	  for ($ii = 0; $ii < count($headers->from); $ii++)      $selected_headers .= 'From: ' . $headers->from[$ii]->mailbox . '@' . $headers->from[$ii]->host . "\n";    for ($ii = 0; $ii < count($headers->to); $ii++)      $selected_headers .= 'To: ' . $headers->to[$ii]->mailbox . '@' . $headers->to[$ii]->host . "\n";    for ($ii = 0; $ii < count($headers->cc); $ii++)      $selected_headers .= 'Cc: ' . $headers->cc[$ii]->mailbox . '@' . $headers->cc[$ii]->host . "\n";    for ($ii = 0; $ii < count($headers->bcc); $ii++)      $selected_headers .= 'Bcc: ' . $headers->bcc[$ii]->mailbox . '@' . $headers->bcc[$ii]->host . "\n";    if (!empty($headers->date))      $selected_headers .= 'Date: ' . $headers->date . "\n";    if (!empty($headers->subject))      $selected_headers .= 'Subject: ' . $headers->subject . "\n";    
	  // see below; getMsg uses global variables    
	  getMsg($mbox, $imap_idx);    $text_part = $plainmsg; 
	  // text portion of the email    
	  $html_part = $htmlmsg; 
	  // html portion of the email    
	  // check for text portion first    
	  $msg_text = trim(strip_tags($plainmsg, '<a>'));    
	  if ($msg_text == '')    {      
		  // text portion is empty, check html portion      
		  $msg_text = trim($htmlmsg);      
		  if ($msg_text == '')      {        
			  // no text or html portion auto-detected, check manually        
			  $msg_text = imap_body($mbox, $imap_idx); 
			  // get the entire raw message        
			  // check for quoted-printable encoding with possible boundary markers and headers at the top        
			  $chunks = explode("\n", trim($msg_text));        
			  if (count($chunks) > 1) 
				  // if there are multiple lines        
			  {          $quoted_printable = false;          if (strpos($chunks[0], '--') === 0) 
				  // if the first line is a boundary marker (starts with '--')          
			  {                        array_shift($chunks); 
			   // remove the first line            
			   if (strpos($chunks[count($chunks) - 1], '--') === 0) 
				   // check the last line            
			   {              array_pop($chunks); 
				// remove that too            
			   }          }          if (strpos(strtolower($chunks[0]), 'content-type') === 0)            array_shift($chunks); 
			   // remove the first line if it's a content-type header          
			   if (strpos(strtolower($chunks[0]), 'content-transfer-encoding') === 0)          {            if (strpos(strtolower($chunks[0]), 'quoted-printable'))              $quoted_printable = true; 
																								// this email was sent using quoted-printable encoding            
																								array_shift($chunks); 
																								// remove the content-transfer-encoding header          
																							   }          $msg_text = implode("\n", $chunks); 
			   // put the remaining lines back together          
			   if ($quoted_printable) $msg_text = quoted_printable_decode($msg_text);          $msg_text = utf8_decode($msg_text);        }      }    }    $from = trim($headers->from[0]->mailbox . '@' . $headers->from[0]->host);    $msgId = isset($headers->message_id) ? trim($headers->message_id) : '';    $time = strtotime($headers->date);    if ($time == 0)      $time = $now;        
	  
	  
	  
	  /******************************************************    At this point:      $headers: the object returned from imap_headerinfo      $selected_headers: text of some headers to display to a user checking mail (subject, from, etc)      $text_part: the text portion, if found      $html_part: the html portion, if found      $msg_text: either the text part, html part, or manually-decoded part (this is the variable to use as email body)      $original_message: the entire unprocessed email body, includingall parts and any attachments      $from: From address      $msgId: message ID from the headers      $time: email delivery time, as a Unix timestamp      $attachments: array of attachments (see below)    ******************************************************/    
	  
	  
	  // process attachments    
	  foreach ($attachments as $filename => $data)    {      
		  // e.g. 
		  file_put_contents('attachments/' . $filename, $data);     }    
	  // flag the email for deletion    
	  imap_delete($mbox, $imap_idx);  }  
	 // delete emails and close the mailbox  
	 imap_expunge($mbox);  imap_close($mbox);}function getMsg($mbox,$mid) {  
	// input 
	$mbox = IMAP stream, $mid = message id  
		// output all the following:  
		global $htmlmsg,$plainmsg,$charset,$attachments;  
	// the message may in $htmlmsg, $plainmsg, or both  
	$htmlmsg = $plainmsg = $charset = '';  $attachments = array();  
	
	// HEADER  
	$h = imap_header($mbox,$mid);  
	// add code here to get date, from, to, cc, subject...  
	
	// BODY  
	$s = imap_fetchstructure($mbox,$mid);  if (empty($s->parts))  
		// not multipart    
		getMsgPart($mbox,$mid,$s,0);  
	// no part-number, so pass 0  
	else {  
		// multipart: iterate through each part    
		foreach ($s->parts as $partno0=>$p)      getMsgPart($mbox,$mid,$p,$partno0+1);  }}function getMsgPart($mbox,$mid,$p,$partno) {  
	// $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart  
	global $htmlmsg,$plainmsg,$charset,$attachments;  
	
	// DECODE DATA  
	$data = ($partno)?    imap_fetchbody($mbox,$mid,$partno):  
	// multipart    
	imap_body($mbox,$mid);  
	// not multipart  
	// Any part may be encoded, even plain text messages, so check everything.  
	if ($p->encoding==4)    $data = quoted_printable_decode($data);  elseif ($p->encoding==3)    $data = base64_decode($data);  
	// no need to decode 7-bit, 8-bit, or binary  
	
	// PARAMETERS  
	// get all parameters, like charset, filenames of attachments, etc.  
	$params = array();  if ($p->ifparameters)    foreach ($p->parameters as $x)      $params[ strtolower( $x->attribute ) ] = $x->value;  if ($p->ifdparameters)    foreach ($p->dparameters as $x)      $params[ strtolower( $x->attribute ) ] = $x->value;  
		
		// ATTACHMENT  
		// Any part with a filename is an attachment,  
		// so an attached text file (type 0) is not mistaken as the message.  
		if (!empty($params['filename']) || !empty($params['name'])) {    
		// filename may be given as 'Filename' or 'Name' or both    
		$filename = (!empty($params['filename']))? $params['filename'] : $params['name'];    
		// filename may be encoded, so see imap_mime_header_decode()    $attachments[$filename] = $data;  
		// this is a problem if two files have same name  
	}  
	// TEXT  
	elseif ($p->type==0 && $data) {    
		// Messages may be split in different parts because of inline attachments,    
		// so append parts together with blank row.    
		if ($p->ifsubtype && strtolower($p->subtype)=='plain')      $plainmsg .= trim($data) ."\n\n";    else      $htmlmsg .= $data ."<br><br>";    $charset = $params['charset'];  
		// assume all parts are same charset  }  
		
		// EMBEDDED MESSAGE  
		// Many bounce notifications embed the original message as type 2,  
		// but AOL uses type 1 (multipart), which is not handled here.  
		// There are no PHP functions to parse embedded messages,  
		// so this just appends the raw source to the main message.  
		elseif ($p->type==2 && $data) {    $plainmsg .= trim($data) ."\n\n";  }  
		
		// SUBPART RECURSION  
		if (!empty($p->parts)) {    foreach ($p->parts as $partno0=>$p2)      getMsgPart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  
								// 1.2, 1.2.1, etc.  
							   }}

?>

 

Share this post


Link to post
Share on other sites

It looks like you added an extra line break on line 73, that should be part of the comment describing the input variables for the getMsg function.

This thread is 6 years old, I'm not using the same computer or living in the same house or working on that project any more.  I don't think I have that code any more.

Share this post


Link to post
Share on other sites

See my previous post.  The code above has a line break on line 73 that shouldn't be there.

Share this post


Link to post
Share on other sites

I do not know why I can not change anything, could you please send me the original file file to my email = oagacino@gmail.com or tell me url where do I download it from?
thank you very much

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

×