设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 303|回复: 1

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

[复制链接]
发表于 2014-2-11 22:47:41 | 显示全部楼层 |阅读模式
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:----------------------

Here's an example of the script I use to check email:
  1. <?php

  2. $now = time(); // current time

  3. $mailbox = '{192.168.150.11:143/imap/novalidate-cert}'; // see http://www.php.net/manual/en/function.imap-open.php
  4. $mbox = imap_open($mailbox, 'username', 'password'); // log in to mail server

  5. if (!$mbox)
  6.   echo ('Failed opening mailbox<br>' . print_r(imap_errors(), true)); // remove the print_r for production use
  7. else
  8. {
  9.   $box = imap_check($mbox); // get the inbox

  10.   for ($imap_idx = 1; $imap_idx <= $box->Nmsgs; $imap_idx++) // loop through the messages
  11.   {
  12.     $headers = imap_headerinfo($mbox, $imap_idx); // http://www.php.net/manual/en/function.imap-headerinfo.php
  13.     $raw_headers = imap_fetchheader($mbox, $imap_idx); // http://www.php.net/manual/en/function.imap-fetchheader.php
  14.     $selected_headers = '';
  15.     $text_part = '';
  16.     $html_part = '';
  17.     $original_message = imap_body($mbox, $imap_idx); // save the copy of the entire thing, attachments and all

  18.     // build selected headers string
  19.     for ($ii = 0; $ii < count($headers->from); $ii++)
  20.       $selected_headers .= 'From: ' . $headers->from[$ii]->mailbox . '@' . $headers->from[$ii]->host . "\n";
  21.     for ($ii = 0; $ii < count($headers->to); $ii++)
  22.       $selected_headers .= 'To: ' . $headers->to[$ii]->mailbox . '@' . $headers->to[$ii]->host . "\n";
  23.     for ($ii = 0; $ii < count($headers->cc); $ii++)
  24.       $selected_headers .= 'Cc: ' . $headers->cc[$ii]->mailbox . '@' . $headers->cc[$ii]->host . "\n";
  25.     for ($ii = 0; $ii < count($headers->bcc); $ii++)
  26.       $selected_headers .= 'Bcc: ' . $headers->bcc[$ii]->mailbox . '@' . $headers->bcc[$ii]->host . "\n";
  27.     if (!empty($headers->date))
  28.       $selected_headers .= 'Date: ' . $headers->date . "\n";
  29.     if (!empty($headers->subject))
  30.       $selected_headers .= 'Subject: ' . $headers->subject . "\n";



  31.     // see below; getMsg uses global variables
  32.     getMsg($mbox, $imap_idx);

  33.     $text_part = $plainmsg; // text portion of the email
  34.     $html_part = $htmlmsg; // html portion of the email

  35.     // check for text portion first
  36.     $msg_text = trim(strip_tags($plainmsg, '<a>'));
  37.     if ($msg_text == '')
  38.     {
  39.       // text portion is empty, check html portion
  40.       $msg_text = trim($htmlmsg);
  41.       if ($msg_text == '')
  42.       {
  43.         // no text or html portion auto-detected, check manually
  44.         $msg_text = imap_body($mbox, $imap_idx); // get the entire raw message
  45.         // check for quoted-printable encoding with possible boundary markers and headers at the top
  46.         $chunks = explode("\n", trim($msg_text));

  47.         if (count($chunks) > 1) // if there are multiple lines
  48.         {
  49.           $quoted_printable = false;
  50.           if (strpos($chunks[0], '--') === 0) // if the first line is a boundary marker (starts with '--')
  51.           {            
  52.             array_shift($chunks); // remove the first line
  53.             if (strpos($chunks[count($chunks) - 1], '--') === 0) // check the last line
  54.             {
  55.               array_pop($chunks); // remove that too
  56.             }
  57.           }
  58.           if (strpos(strtolower($chunks[0]), 'content-type') === 0)
  59.             array_shift($chunks); // remove the first line if it's a content-type header
  60.           if (strpos(strtolower($chunks[0]), 'content-transfer-encoding') === 0)
  61.           {
  62.             if (strpos(strtolower($chunks[0]), 'quoted-printable'))
  63.               $quoted_printable = true; // this email was sent using quoted-printable encoding
  64.             array_shift($chunks); // remove the content-transfer-encoding header
  65.           }
  66.           $msg_text = implode("\n", $chunks); // put the remaining lines back together
  67.           if ($quoted_printable) $msg_text = quoted_printable_decode($msg_text);
  68.           $msg_text = utf8_decode($msg_text);
  69.         }
  70.       }
  71.     }

  72.     $from = trim($headers->from[0]->mailbox . '@' . $headers->from[0]->host);
  73.     $msgId = isset($headers->message_id) ? trim($headers->message_id) : '';

  74.     $time = strtotime($headers->date);
  75.     if ($time == 0)
  76.       $time = $now;

  77.    
  78.     /******************************************************
  79.     At this point:
  80.       $headers: the object returned from imap_headerinfo
  81.       $selected_headers: text of some headers to display to a user checking mail (subject, from, etc)
  82.       $text_part: the text portion, if found
  83.       $html_part: the html portion, if found
  84.       $msg_text: either the text part, html part, or manually-decoded part (this is the variable to use as email body)
  85.       $original_message: the entire unprocessed email body, includingall parts and any attachments
  86.       $from: From address
  87.       $msgId: message ID from the headers
  88.       $time: email delivery time, as a Unix timestamp
  89.       $attachments: array of attachments (see below)
  90.     ******************************************************/

  91.     // process attachments
  92.     foreach ($attachments as $filename => $data)
  93.     {
  94.       // e.g. file_put_contents('attachments/' . $filename, $data);
  95.     }

  96.     // flag the email for deletion
  97.     imap_delete($mbox, $imap_idx);
  98.   }

  99.   // delete emails and close the mailbox
  100.   imap_expunge($mbox);
  101.   imap_close($mbox);
  102. }



  103. function getMsg($mbox,$mid) {
  104.   // input $mbox = IMAP stream, $mid = message id
  105.   // output all the following:
  106.   global $htmlmsg,$plainmsg,$charset,$attachments;
  107.   // the message may in $htmlmsg, $plainmsg, or both
  108.   $htmlmsg = $plainmsg = $charset = '';
  109.   $attachments = array();

  110.   // HEADER
  111.   $h = imap_header($mbox,$mid);
  112.   // add code here to get date, from, to, cc, subject...

  113.   // BODY
  114.   $s = imap_fetchstructure($mbox,$mid);
  115.   if (empty($s->parts))  // not multipart
  116.     getMsgPart($mbox,$mid,$s,0);  // no part-number, so pass 0
  117.   else {  // multipart: iterate through each part
  118.     foreach ($s->parts as $partno0=>$p)
  119.       getMsgPart($mbox,$mid,$p,$partno0+1);
  120.   }
  121. }

  122. function getMsgPart($mbox,$mid,$p,$partno) {
  123.   // $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart
  124.   global $htmlmsg,$plainmsg,$charset,$attachments;

  125.   // DECODE DATA
  126.   $data = ($partno)?
  127.     imap_fetchbody($mbox,$mid,$partno):  // multipart
  128.     imap_body($mbox,$mid);  // not multipart
  129.   // Any part may be encoded, even plain text messages, so check everything.
  130.   if ($p->encoding==4)
  131.     $data = quoted_printable_decode($data);
  132.   elseif ($p->encoding==3)
  133.     $data = base64_decode($data);
  134.   // no need to decode 7-bit, 8-bit, or binary

  135.   // PARAMETERS
  136.   // get all parameters, like charset, filenames of attachments, etc.
  137.   $params = array();
  138.   if ($p->ifparameters)
  139.     foreach ($p->parameters as $x)
  140.       $params[ strtolower( $x->attribute ) ] = $x->value;
  141.   if ($p->ifdparameters)
  142.     foreach ($p->dparameters as $x)
  143.       $params[ strtolower( $x->attribute ) ] = $x->value;

  144.   // ATTACHMENT
  145.   // Any part with a filename is an attachment,
  146.   // so an attached text file (type 0) is not mistaken as the message.
  147.   if (!empty($params['filename']) || !empty($params['name'])) {
  148.     // filename may be given as 'Filename' or 'Name' or both
  149.     $filename = (!empty($params['filename']))? $params['filename'] : $params['name'];
  150.     // filename may be encoded, so see imap_mime_header_decode()
  151.     $attachments[$filename] = $data;  // this is a problem if two files have same name
  152.   }

  153.   // TEXT
  154.   elseif ($p->type==0 && $data) {
  155.     // Messages may be split in different parts because of inline attachments,
  156.     // so append parts together with blank row.
  157.     if ($p->ifsubtype && strtolower($p->subtype)=='plain')
  158.       $plainmsg .= trim($data) ."\n\n";
  159.     else
  160.       $htmlmsg .= $data ."<br><br>";
  161.     $charset = $params['charset'];  // assume all parts are same charset
  162.   }

  163.   // EMBEDDED MESSAGE
  164.   // Many bounce notifications embed the original message as type 2,
  165.   // but AOL uses type 1 (multipart), which is not handled here.
  166.   // There are no PHP functions to parse embedded messages,
  167.   // so this just appends the raw source to the main message.
  168.   elseif ($p->type==2 && $data) {
  169.     $plainmsg .= trim($data) ."\n\n";
  170.   }

  171.   // SUBPART RECURSION
  172.   if (!empty($p->parts)) {
  173.     foreach ($p->parts as $partno0=>$p2)
  174.       getMsgPart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
  175.   }
  176. }

  177. ?>
复制代码

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.                                                                               
 楼主| 发表于 2014-2-11 22:51:27 | 显示全部楼层
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"
  1. //Test code for email message.
  2.                         $open_email_msg =  file_get_contents('emailmessage.html');
  3.                         //A script that searches the e-mail for the string News Update, and if it is found it will start the function NewsUpdate
  4.                         if(strpos($open_email_msg,"News Update"))
  5.        
  6.                                 function NewsUpdate($open_email_msg) {
  7.                        
  8. //Login to MySQL Datebase
  9. $hostname = "localhost";
  10. $db_user = "user";
  11. $db_password = "pass";
  12. $database = "tablename";
  13. $db_table = "bx_news_entries";

  14. $db = mysql_connect($hostname, $db_user, $db_password);
  15. mysql_select_db($database,$db);

  16. $subject = 'Test News Article';
  17. $tags = str_replace(' ',',',$subject); //DDIE
  18. $uri =  str_replace(' ','-',$subject); //DDIE
  19. $when = strtotime("now");        //date article was posted
  20. $categories = 'Events';
  21. $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.';
  22. $snippet = 'Lorem ipsum dolor sit amet.';

  23. //$snippet = explode(".", $content, -1);



  24. # THIS CODE WILL TELL MYSQL TO INSERT THE DATA FROM THE EMAIL INTO YOUR MYSQL TABLE
  25. $sql = "INSERT INTO $db_table(`caption`,`snippet`,`content`,`when`,`uri`,`tags`,`categories`,`DATE`) values ('$subject','$snippet','$content','$when','$uri','$tags','$categories','$when')";
  26. if($result = mysql_query($sql ,$db)) {
  27. } else {
  28. echo "ERROR: ".mysql_error();
  29. }
  30. echo "<h1>News Article added!</h1>";

  31. }

  32.         else {
  33. echo "<h3>'News Update</h3>not found in e-mail message!";
  34. }

  35. ?>
复制代码


您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-26 13:51 , Processed in 0.013869 second(s), 17 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表