Jump to content

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


IanArcher

Recommended Posts

How can I make it so when I e-mail for e.g. news@example.com text/information of the e-mail is written into a mysql table? It would extract the contents of a new email and write them into MySQL table. This table manages news articles on the website, so in the MySQL columns:"content" is the body of the message"caption" is the title of the news article"snippet" is the title that will appear in a "Latest News" block"uri""date" is the date the article is posted." $subject = caption = uri $message = content = snippet(first two lines of content) $date = date (in Unix timestamp) The table is named bx_news_entries manages the news articles visibly.I researched and saw a user who posted this on stackoverflow who's code looked like so:

<?php$imap = imap_open("{gmail.com}", "username", "password"); if( $imap ) { 	 //Check no.of.msgs	 $num = imap_num_msg($imap) 	 //if there is a message in your inbox	 if( $num >0 ) {		  //read that mail recently arrived		  echo imap_qprint(imap_body($imap, $num));	 } 	 //close the stream	 imap_close($imap);}?> We are using an exchange server..I am a coop student so I am not really advanced at this. I tried this as a test to see if it works, logging in gmail to read email. It didnt work. <?php // connect to the mailbox$m_mail = imap_open("{mail.https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2}INBOX", "username", "password"); //get all messages$m_search=imap_search ($m_mail, 'ALL ');  // Order results starting from newest messagersort($m_search); //loop through and do what's necessaryforeach ($m_search as $onem) { 	//get imap header info for obj thang	$headers = imap_headerinfo($m_mail, $onem);	$head = imap_fetchheader($m_mail, $headers->Msgno);	$body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );   echo $body; } //purge messages (if necessary)imap_expunge($m_mail); //close mailboximap_close($m_mail); ?>  

I have the code imagined in my head, i just need to bring it to fruition.Can somebody assist me with this please?

Link to comment
Share on other sites

Which parts do you need help with? I have a better mail checking script at home I can post later that will handle different encodings, multiple email parts, attachments, etc.
Pretty much in the first post. It is not a g-mail account, it is a private e-mail on my server. Though I don't know how to find out the imap host for it in cpanel. This is how it looks:2rwuo1u.jpg Lets say the e-mail is aligned to like this on particular lines so the script would know which line would go into which column in the table.From: admin@example.comTo: newsfeed@example.comSubject: Test News Article! <--- This would serve as the caption and uri for the news article, and would go into the caption column and uri column. test news article <--- (Line 1:) This line would be for the tags that get inserted into the tags column12/20/2011 <--- (Line 2:) This line would go into the date column but would have to be converted to Unix timestamp (Line 3, based on line breaks,) Would be the message that gets inserted into the content column, and the first line only would automatically be inserted into the snippet column<p>Hello. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> How could i attain this?
Link to comment
Share on other sites

If the email server is the same as the web server, then the hostname is "localhost". If it is a text email and all you want to do is split up the lines, then you can use the explode function on the message body to get an array of lines, and access the lines directly. To convert the date you can use strtotime, or you can explode the date and use mktime. http://www.php.net/manual/en/function.explode.phphttp://www.php.net/manual/en/function.strtotime.phphttp://www.php.net/manual/en/function.mktime.php If it's an HTML email then you'll need more complex rules to figure out which content you want.

Link to comment
Share on other sites

If the email server is the same as the web server, then the hostname is "localhost". If it is a text email and all you want to do is split up the lines, then you can use the explode function on the message body to get an array of lines, and access the lines directly. To convert the date you can use strtotime, or you can explode the date and use mktime. http://www.php.net/m...ion.explode.phphttp://www.php.net/m...n.strtotime.phphttp://www.php.net/m...tion.mktime.php If it's an HTML email then you'll need more complex rules to figure out which content you want.
I checked out some of those earlier, but i'll take a better look, Also will you still be able to post your better script that you have home here later today?
Link to comment
Share on other sites

By the way, It is an HTML email because in the content column of bx_news_entries table, there are HTML formatting tags before text to split up the paragraphs, such as <p>Hi there, sentence, sentence, sentence</p><p>The new art exhibit beings as follows,</p><p>March 23, 2011</p><p>March 30th, 2011</p> Essentially as i observe it in the table, the <p> tags serve as <br /> tags strangely. Also, In my original post, would the code that i said somebody else wanted to use for the similar initiative, work for mines?

Edited by IanArcher
Link to comment
Share on other sites

If it's an HTML email then you'll need more complex rules to figure out which content you want.
What were those complex rules your were talking about? I might need to explore those options.Though What would be the most straight forward way of doing this effectively using PHP?
Link to comment
Share on other sites

You can either use something like DOMDocument to load the HTML into a DOM object and then traverse the DOM like you would in Javascript, or use regular expressions to grab the text inside certain tags. If the HTML is simple and doesn't change then you may be able to use the string functions to extract what you're looking for. It depends on the format of the email.

Link to comment
Share on other sites

If the email format every time strictly maintain this format:

Test News Article! <--- This would serve as the caption and uri for the news article, and would go into the caption column and uri column.test news article <--- (Line 1:) This line would be for the tags that get inserted into the tags column12/20/2011 <--- (Line 2:) This line would go into the date column but would have to be converted to Unix timestamp(Line 3, based on line breaks,) Would be the message that gets inserted into the content column, and the first line only would automatically be inserted into the snippet column<p>Hello. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
The very first line in the e-mail would always be the subject, and php would define it as $caption and $uriThe very second line in the e-mail would always be the tags and php would define it as $tagsThe very third line in the e-mail would always be the date and php would define it as $date and then use either mktime or strtotime as a conversion to Unix timestamp.The very fourth line in the e-mail would always be the message and php would define it as $message and would use explode() to split up to the very first line and define it as $snippet and $snippet would be inserted into the uri column in bx_news_entries.The very fifth line in the e-mail would always be the category name and PHP would define it as $category and insert it into the category column.
$m_mail = imap_open("{server.myhost.com}INBOX", "username", "password");//get all messages$m_search=imap_search ($m_mail, 'ALL ');// Order results starting from newest messagersort($m_search);//loop through and do what's necessaryforeach ($m_search as $onem) {    //get imap header info for obj thang    $headers = imap_headerinfo($m_mail, $onem);    $head = imap_fetchheader($m_mail, $headers->Msgno);    $body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );    $line1    = find('First Line', =>$caption, $m_search);    $line1_2    = find('First Line', =>$uri, $m_search);    $line2    = find('Second Time', =>$tags, $m_search);    $line3    = find('Third Line', =>$date, $m_search);    strtotime($date, =>$date);    $line4    = find('Fourth Line', =>$message, $m_search);    explode($message at first 2 lines, $snippet);    $line5    = find('Fifth Line', =>$category, $m_search);        //DO WHAT YOU NEED TO DO HERE - insert to the database, etc    //Need to also access permissions to the website as an admin to feature features that allow posting to BxNewsEntries. BxNewsEntries is a MySQL table that holds the info for the news postings.    $hostname = "localhost"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost    $db_user = "username"; // change to your database password    $db_password = "password"; // change to your database password    $database = "database"; // provide your database name    $db_table = "bx_news_entries"; // leave this as is    $db = mysql_connect($hostname, $db_user, $db_password);    mysql_select_db($database,$db);    $sql = "INSERT INTO $db_table(id,author_id,caption,snippet,content,when,uri,tags,categories,comment,vote,date,status,featured,rate,rate_count,view_count,cmts_count) values    ('".mysql_real_escape_string(stripslashes($_REQUEST['$caption']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$snippet']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$content']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$uri']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$tags']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$categories']))."',        '".mysql_real_escape_string(stripslashes($_REQUEST['$date']))."',";                                        if($result = mysql_query($sql ,$db)) {                    } else {                    echo "ERROR: ".mysql_error();                    }                    } else {}//purge messages (if necessary)imap_expunge($m_mail);//close mailboximap_close($m_mail);

This is really how i imagine it in my head, i can see it's obviously not correct functions but i honestly need some serious help with this, maybe if you were to type an example of an effective code please?

Link to comment
Share on other sites

That's not really a format so much as a description. You said this is an HTML email, so the format includes all of the HTML tags in the email. If the "first line" appears in a div tag with a specific ID or class, for example, then you can use a regular expression to look for the contents of that div tag. You need to figure out exactly how the HTML that you're trying to read is structured, not just a description of what the rendered output looks like. You can get that from the email though if you don't know what it is.Here's an example of the script I use to check email:

<?php$now = time(); // current time$mailbox = '{192.168.150.11:143/imap/novalidate-cert}'; // see http://www.php.net/manual/en/function.imap-open.php $mbox = imap_open($mailbox, 'username', 'password'); // log in to mail serverif (!$mbox)  echo ('Failed opening mailbox<br>' . print_r(imap_errors(), true)); // remove the print_r for production useelse{  $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.  }}?>

Print out the $text_part, $html_part, and $msg_text variables in that loop to figure out which one you want to use. Maybe the email has a text portion that is easier to process.Once you get the text you're looking for, you need to use strip_tags to remove all of the HTML from that text if you're going to display it on a page. You don't need people emailing you Javascript code or Flash movies that you happily save and display for your users.

  • Like 2
Link to comment
Share on other sites

I am at a point in applying a test for the overall code before incorporating the email script justsomeguy provided.Haven't really create my own function before, so what i am attempting is to start the scripts below the line "function NewsUpdate" but i want them to be apart of the function. In the if statement, when the script finds the string "News Update" in the 'email message' it will start those scripts if to (the else statement all the way at the bottom) it will fail and say "News Update not found in e-mail message" But i get the error:Parse error: syntax error, unexpected T_FUNCTION What am i doing wrong?

//Test code for email message.			$open_email_msg =  file_get_contents('emailmessage.html');			//A script that searches the e-mail for the string News Update, and if it is found it will start the function NewsUpdate			if(strpos($open_email_msg,"News Update"))					function NewsUpdate ($open_email_msg) {			//Login to MySQL Datebase$hostname = "localhost";$db_user = "user";$db_password = "pass";$database = "tablename";$db_table = "bx_news_entries"; $db = mysql_connect($hostname, $db_user, $db_password);mysql_select_db($database,$db); $subject = 'Test News Article';$tags = str_replace(' ',',',$subject); //DDIE$uri =  str_replace(' ','-',$subject); //DDIE$when = strtotime("now");	//date article was posted$categories = 'Events';$content = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.';$snippet = 'Lorem ipsum dolor sit amet.'; //$snippet = explode(".", $content, -1);   # THIS CODE WILL TELL MYSQL TO INSERT THE DATA FROM THE EMAIL INTO YOUR MYSQL TABLE$sql = "INSERT INTO $db_table(`caption`,`snippet`,`content`,`when`,`uri`,`tags`,`categories`,`DATE`) values ('$subject','$snippet','$content','$when','$uri','$tags','$categories','$when')";if($result = mysql_query($sql ,$db)) {} else {echo "ERROR: ".mysql_error();}echo "<h1>News Article added!</h1>"; } 	else {echo "<h3>'News Update</h3>not found in e-mail message!";} ?>

Edited by IanArcher
Link to comment
Share on other sites

I moved my function above and called it and it worked.

function NewsUpdate ($open_email_msg) {	//function declaration} //Test code for email message. $open_email_msg =  file_get_contents('emailmessage.html'); //A script that searches the e-mail for the string News Update, and if it is found it will start the function NewsUpdate if(strpos($open_email_msg,"News Update"))	NewsUpdate ($open_email_msg);else { 	echo "<h3>'News Update</h3>not found in e-mail message!"; } 

Edited by IanArcher
Link to comment
Share on other sites

I am trying to get the scripts to search the $open_email_msg which different e-mails will have different info but the same format as below. I just want whatever they put after Title: or Tags: or Categories: whatever that data is to be captured and not the string "Title:" or "Tags:" or "Categories:" This is just a snippet of the whole code, the rest inserts the info into a MySQL table and then is posted to a News Article on the site.Can somebody help me find a solution to this please?Strict e-mail message format:

News Update Title: Article Title Tags: tag1 tag2Categories: Article Category, 2nd Article CategorySnippet: Article snippet. Message:Article Message. Images. More text, more text. Lorem impsum dolor sit amet.
    <?php    //These functions searches the open e-mail for the the prefix defining strings.        //Need a function to search after the space after the strings because the subject, categories, snippet, tags and message are constant-changing.    $subject = strpos($open_email_msg, "Title:");        //Searches the open e-mail for the string "Title"    $categories = strpos($open_email_msg, "Categories:");        //Searches the open e-mail for the string "Categories"    $snippet = strpos($open_email_msg,"Snippet");            //Searches the open e-mail for the string "Snippet"    $content = strpos($open_email_msg, "Message");    //Searches the open-email for the string "Message"    $tags = str_replace(' ',',',$subject); //DDIE    $uri =  str_replace(' ','-',$subject); //DDIE    $when = strtotime("now");    //date article was posted        ?>

Link to comment
Share on other sites

Use a regular expression to get the data, check some of the examples and comments here: http://www.php.net/manual/en/function.preg-match.php To get the data on a single line (multiple lines won't work for this, it will only get the first line), the pattern would look something like this: #^Title:(.*)$#m That looks for the start of a line, then "Title:", then matches any number of characters to the end of the line. http://www.php.net/manual/en/pcre.pattern.php

Link to comment
Share on other sites

Use a regular expression to get the data, check some of the examples and comments here: http://www.php.net/m....preg-match.php To get the data on a single line (multiple lines won't work for this, it will only get the first line), the pattern would look something like this: #^Title:(.*)$#m That looks for the start of a line, then "Title:", then matches any number of characters to the end of the line. http://www.php.net/m...cre.pattern.php
Would you recommend something like this
preg_match_all('/([^:\\s]+): (.+)/', $open_email_msg, $matches, PREG_SET_ORDER); echo '<pre>' . print_r($matches, 1) . '</pre>'; 

I used this code

           	 $subject = explode("Title: ", $open_email_msg);     // Replace with whatever the line separator is                foreach($subject as $line){                    $temp = explode(": ", $line, 2);                    $msg[$temp[0]] = $temp[1];                }                $categories = explode("Categories: ", $open_email_msg);     // Replace with whatever the line separator is                foreach($categories as $line){                    $temp = explode(": ", $line, 2);                    $msg[$temp[0]] = $temp[1];                }                $snippet = explode("Snippet: ", $open_email_msg);     // Replace with whatever the line separator is                foreach($snippet as $line){                    $temp = explode(": ", $line, 2);                    $msg[$temp[0]] = $temp[1];                }                $content = explode("Message: ", $open_email_msg);     // Replace with whatever the line separator is                foreach($content as $line){                    $temp = explode(": ", $line, 2);                    $msg[$temp[0]] = $temp[1];                }

But all it did was give me the word "Array" in multiple columns in the MySQL table.

Edited by IanArcher
Link to comment
Share on other sites

Add some code to show you what that is doing:

$subject = explode("Title: ", $open_email_msg); echo '$subject: <pre>' . print_r($subject, true) . '</pre><br>';foreach($subject as $line){    echo '$line: "' . $line . '"<br>';  $temp = explode(": ", $line, 2);   echo '$temp: <pre>' . print_r($temp, true) . '</pre><br>';    $msg[$temp[0]] = $temp[1];}echo '$msg: <pre>' . print_r($msg, true) . '</pre><br>';

Link to comment
Share on other sites

  • 2 weeks later...

I have overcome alot on my own while the forums here were down. But im stuck another issue.Images inserted into the emails cannot be seen on a web browser, because it was inserted into that emailSo the image reference in the source code has to be a hyperlink reference to the image and not cid:image001@1CCC701.5A896430My issue is there may be one or more images inserted in that email to be published to the site, so how would i be able to differentiate and upload themto a specified FTP server folder and also get the uploaded file as use the hyperlink reference as a string to be replaced with the current as seen below.In the body source, the image reference is:<img width=183 height=183 id="Picture_x0020_1" src="cid:image001.png@01CCC701.5A896430">Below is the code as i imagine it in my head. Could somebody help me find a solution to this?

<?php//Specifies e-mail server inbox and connects to it    $mailbox = '{server.example.com/imap/novalidate-cert}INBOX';    $mbox = imap_open($mailbox, 'user', 'pass'); // log in to mail server//Sets up FTP connection    $ftp_server = "ftp.example.com";    $ftp_user = "user";    $ftp_pass = "pass";//Login with username and password    $conn = ftp_connect($ftp_server);    $login = ftp_login($conn, $ftp_user, $ftp_pass);// the body of the e-mail body with its original formatting quoted-printable characters to an 8-bit character set$body = imap_qprint(imap_fetchbody($mbox, $no, "1.2"));//CID image names will be dynamic so i must use REGEX    $fileto = "/src="cid:(.*).png@(.*)/"";    #$fileto = "/src="cid:(.*).bmp(.*)/"";    #$fileto = "/src="cid:(.*).png(.*)/"";    #$fileto = "/src="cid:(.*).gif(.*)/"";        $target_f = "public_html/images/";    if(strpos($body, $fileto) {        $remote_f = ftp_nb_put($conn, $target_f, $fileto, FTP_ASCII);    } or die "Could not convert image!";        $new_img = str_replace($fileto, $remote_f, $body);        ftp_close ($conn);    ?>

Link to comment
Share on other sites

I originally sent a test email message with the format for posting to the table to the email account with a sample image, and when i checked the original message in Microsoft Outlook that i sent, there is an option for downloading all attachments from the email but there wasnt any attachements found in the email, so the image doesn't count as an attachment, because i had considered going down that path of extracting attachments but coming across this finding in Outlook means that would've probably been a dud. What do you think? EDIT:So i found obtained the source of the e-mail i sent through (On hotmail.com, not Outlook) and here is a paste of the what i believe is MIME? text of the imagehttp://pastebin.com/VDzHqVnr

Edited by IanArcher
Link to comment
Share on other sites

The images are attachments, Outlook just handles it differently. Check the return values you get from the function that actually parses the email, it extracts attachments as well. Don't rely on a full-blown mail client like Outlook to tell you what the format of the email was, the client will transform it to make it "user-friendly". You don't want user-friendly, you need to know exactly what is going on under the hood.

Link to comment
Share on other sites

Here is the complete script at the moment, mind taking a look (justsomeguy), not asking to be spoonfed or anything:

//IMAP Functions begin here (Before NewsUpdate function)  //Accessing e-mail inbox  $mailbox = '{server.com/imap/novalidate-cert}INBOX';  $mbox = imap_open($mailbox, 'user', 'pass'); // log in to mail server  //Sets up FTP connection   $ftp_server = "ftp.example.com";   $ftp_user = "user";   $ftp_pass = "pass";     //Login with username and password	$conn = ftp_connect($ftp_server);	$login = ftp_login($conn, $ftp_user, $ftp_pass);#  #	Images inserted into the emails cannot be seen on a web browser, because it was inserted into that email#	So the image reference in the source code has to be a hyperlink reference to the image and not cid:image001@1CCC701.5A896430#	My issue is there may be one or more images inserted in that email to be published to the site, so how would i be able to differentiate  and upload them#	to a specified FTP server folder and also get the uploaded file as use the hyperlink reference as a string to be replaced with the current as seen below.#	In the body source, the image reference is:#	 <img width=183 height=183 id="Picture_x0020_1" src="cid:image001.png@01CCC701.5A896430">#						 to become#	 <img width=183 height=183 id="Picture_x0020_1" src="image001.png">#   $no = 4;   //number of the e-mail message. Defined as first e-mail in the inbox (not a UID)    $open_email_msg = imap_body($mbox, $no);     $body = imap_qprint(imap_fetchbody($mbox, $no, "1.2"));   /* Attempts to save the body using file_get_contents and file_put_contents  	  $bodyExtract = file_get_contents($body);	  $bodySave = file_put_contents('bodyhold.html', $bodyExtract);	  //$tempFile = file_get_contents('bodyhold.html');		*/     echo $body;   # if (strpos($bodyExtract, '/src="cid:(.*)"/')  #  {  #   $tempfile->$body //invalid statements, if properly executed this would put the copied body file exactly where the body used to be, not exactly retrieving the image      #  }       //The following sequence defines the function "NewsUpdate"	function NewsUpdate ($open_email_msg, $body)	{	  //Login to MySQL Datebase	  $hostname = "localhost";	  $db_user = "user";	  $db_password = "pass";	  $database = "database";	  $db_table = "table";	  $db = mysql_connect($hostname, $db_user, $db_password);	  mysql_select_db($database,$db);	  //These functions searches the open e-mail for the the prefix defining strings.	   //Need a function to search after the space after the strings because the subject, categories, snippet, tags and message are constant-changing.	   $subject = preg_match('/Title: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';		$subject = str_replace("Title: ", "" ,$subject);	  	   $categories = preg_match('/Categories: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';  //Searches the open e-mail for the string "Categories"		$categories = str_replace("Categories: ", "" ,$categories);	  	   $tags = preg_match('/Tags: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';  //Searches the open e-mail for the string "Tags"		$tags = str_replace("Tags: ", "" ,$tags);	  	   //Alternative function for defining categories	   # $categories = str_replace(' ',',',$subject);	   $snippet = preg_match('/Snippet: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';	 //Searches the open e-mail for the string "Snippet"		$snippet = str_replace("Snippet: ", "" ,$snippet);##########################################################	  	   $content = preg_match('/Message: (.*)/', $body, $matches) ? $matches[1] : '';	//Searches the open-email for the string "Message"		$content = str_replace("Message: ", "" ,$content);	  #########################################################	  	#   $uri = str_replace(" ", "-", $subject); //uri of news article	   //This defines the article's tags	#   $tags = str_replace(' ',',',$subject);  //DDIE	  	   $when = strtotime("now");  //date article was posted   	  # THIS CODE WILL TELL MYSQL TO INSERT THE DATA FROM THE EMAIL INTO YOUR MYSQL TABLE	 $sql = "INSERT INTO $db_table(`caption`,`snippet`,`content`,`when`,`tags`,`categories`,`DATE`) values ('$subject','$snippet','$content','$when','$tags','$categories','$when')";	  if($result = mysql_query($sql ,$db)) {	  } else {	  echo "ERROR: ".mysql_error();	  }	  //echo "<h1>News Article added!</h1>"; //uncomment for testing purposes	} //end defining the function NewsUpdate     //This script that searches the e-mail for the string "News Update", and if it is found it will start the function NewsUpdate   //if(strpos($open_email_msg,"News Update"))  	NewsUpdate ($open_email_msg, $body);  //calls the function NewsUpdate  #   else {#	  echo "<b>News Update</b> not found in e-mail message!";#	  }  	   //Deletes the email	   imap_delete($mbox, $no);#	 imap_expunge($mbox);  imap_close($mbox); //closes the mailbox  ftp_close ($conn); //closes the ftp connection ?>

Edited by IanArcher
Link to comment
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
×
×
  • Create New...