Question : How do I get this PHP IMAP script to fetch the body of emails?  I can't get it to work.

...I've left out the username and password to the mail server of course..


<?php

function translate_object($obj){
 return $obj->mailbox.'@'.$obj->host;

}

/* connect to gmail */
$hostname = '{10.2.1.248:995/pop3/ssl/novalidate-cert}INBOX';
$username = 'not shown';
$password = 'not shown';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());

/* grab emails */
$emails = imap_search($inbox,'ALL');

$headers = @imap_headers($inbox) or die("Couldn't get emails");

$numEmails = sizeof($headers);

$num = imap_num_msg($inbox);

echo "You have $numEmails in your mailbox<br /><br />";

$message_count = imap_num_msg($inbox);

$body = trim(substr(imap_body($inbox), 0, 10));


for($i = 1; $i < $numEmails+1; $i++)

{

$mailHeader = @imap_headerinfo($inbox, $i);

$from = $mailHeader->reply_toaddress;

$subject = strip_tags($mailHeader->subject);

$date = $mailHeader->date;



echo "<strong>From:</strong>".implode(',',array_map('translate_object',$mailHeader->from))."<br /> <strong>Subject:</strong> $subject<br /><strong>Date:</strong> $date<br />Message: $body<br />";

}

/* close the connection */
imap_close($inbox);

?>

Answer : How do I get this PHP IMAP script to fetch the body of emails?  I can't get it to work.

Here is how I did it in one of my scripts several years ago.

This script was used to capture email from baseball league managers reporting scores via email. The subject had to be formatted like this:
Score-221-4-0-42

Meaning that this is the score being reported for game#221 with the score 4-0 with team 42 reporting the score.
I had the game data updated and sent a notification email to the webmaster, league president and the team that reported the score.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
<? 
       // Debug Flag
       $debug = False;
       $reportemail    = '[email protected]';
       $presidentemail = '[email protected]';
       $webmasteremail = '[email protected]';
       //$pwd            = 'password';

       //check for new messages 
       $mailbox = imap_open("{localhost/pop3:110}INBOX", '[email protected]', 'password'); 
       if ($mailbox)
       {
         // Check messages 
         $check = imap_check($mailbox); 
         if ($debug) {
           print("<HTML>");
           print("  <HEAD>");
           print("    <TITLE>imap_check</TITLE>");
           print("  </HEAD>");
           print("  <BODY>");
           print("    <PRE>"); 
           print("      Date most recent message : " . $check->Date); 
           print("      <BR>"); 
           print("      Connection type : " . $check->Driver); 
           print("      <BR>"); 
           print("      Name of the mailbox : " . $check->Mailbox); 
           print("      <BR>"); 
           print("      Number of messages : " . $check->Nmsgs); 
           print("      <BR>"); 
           print("      Number of recent messages : " . $check->Recent); 
           print("      <BR>"); 
           print("    </PRE>"); 
         }

         // Gonna have to loop and find the new messages that
         // we have not yet parsed. store the last message num
         // in a text file.
         // Open the counter file and get the last message checked.
         // then loop through the messages beginning at the last 
         // message checked + 1.
         $lastmsg = file_get_contents('msgcounter.dat') + 1;
         // Get header for message(s)

         for ($index = $lastmsg-1; $index <= $check->Nmsgs; $index++ ) {
           $games = array();
           $recips = array();
           $header = imap_header($mailbox, $index); 
           if ($debug) {
             print("    <HR><PRE>"); 
             print("      Header Date : " . $header->Date . "<BR>"); 
             $toname    = $header->to[0]->personal;
             $toaddress = "&lt;".$header->to[0]->mailbox."@".$header->to[0]->host."&gt;";
             print("Header To : " . $toname." ".$toaddress . "<BR>");    
             $fromname    = $header->from[0]->personal;
             $fromaddress = "&lt;".$header->from[0]->mailbox."@".$header->from[0]->host."&gt;";
             print("Header From : " . $fromname." ".$fromaddress . "<BR>"); 
             print("      Header cc : " . $header->cc . "<BR>"); 
             print("      Header ReplyTo : " . $header->ReplyTo . "<BR>"); 
             print("      Header Subject : " . $header->Subject . "<BR></PRE>"); 
             print("    <PRE>"); 
             print(      htmlspecialchars(quoted_printable_decode(imap_body($mailbox,$index)))); 
             print("    </PRE></BODY></HTML>"); 
           } else {
             // Score-221-4-0-42
             list($sub, $gamenum, $visitorscore, $homescore, $teamnum) = split("-", $header->Subject );
             // Now update the games table ONLY if the vaiable $sub = 'Score'
             if (strcasecmp($sub, 'SCORE') == 0) {
               $sql =  "update games \n";
               $sql .= "set visitorscore =". $visitorscore.", homescore = ".$homescore. "\n";
               $sql .= "where gamenum = ".$gamenum." and \n";
               $sql .= "  (\n";
               $sql .= "    (homeid = ".$teamnum.")\n";
               $sql .= "    or \n";
               $sql .= "    (visitorid = ".$teamnum.")\n";
               $sql .= "  )\n";
               // Do DB stuff here...
               print($sql);
               // Add to $games array for later reporting
               array_push($games,array($gamenum, $visitorscore, $homescore)); 

               // add the sender of this email to $recips array 
               // for later sending confirmation email
               $fromname    = $header->from[0]->personal;
               $fromaddress = "<".$header->from[0]->mailbox."@".$header->from[0]->host.">";
               array_push($recips, $fromname." ".$fromaddress); 
             }
             imap_close($mailbox); 
    
             // Store the last checked message number to the counter file.
             print($index."\n");
             //file_put_contents('msgcounter.dat', $index);             
             if (!$handle = fopen('msgcounter.dat', 'w')) {
               echo "Cannot open file ('msgcounter.dat')";
               exit;
             }

            // Write $index to our opened file.
            if (fwrite($handle, $index) === FALSE) {
              echo "Cannot write to file ('msgcounter.dat')";
              exit;
            }     
            fclose($handle);

           }
         }
         // Now send confirmations to the Message Sender, League President and the Webmaster
         $headers  = "MIME-Version: 1.0\n";
         $headers .= "Content-type: text/plain; charset=iso-8859-1\n";
         $headers .= "X-Priority: 3\n";
         $headers .= "X-MSMail-Priority: Normal\n";
         $headers .= "X-Mailer: php\n";
         $headers .= "From: \"Automated Scores\" <".$reportemail.">\n";
         $message  = "The score for these game(s) have been reported:\n";
         for ($i = 0; $i <= count($games); $i++) {
           $message .= print_r($games)."\n"; 
         }
         mail($presidentemail, 'Score Reported' + $header->Subject, $message, $headers);
         mail($webmasteremail, 'Score Reported' + $header->Subject, $message, $headers);
         for ($i = 0; $i <= count($recips); $i++) {
           mail($recips[$i], 'Score Reported' + $header->Subject, $message, $headers);
         }
       } else {
         print("Can't open mailbox");
       }
?> 
Random Solutions  
 
programming4us programming4us