Thanks to PHP, we can check our email account remotely using PHP and its imap_xxx functions, which allow us to communicate with mail servers via IMAP, POP3 or NNTP protocols. In this article Mitchell shows us how to create a completely web-based email checking script which can also delete, send and reply to emails... all using only PHP's IMAP functions.
Create Your Own Mail Script With PHP and IMAP - The ShowEmail function and more (Page 5 of 6 )
ShowEmail connects to our IMAP server using imap_open and retrieves both the header and body details of one specific email. As we saw earlier, imap_headerinfo returns the header details of an email as an array, like this:
$mailHeader = @imap_headerinfo($conn, $id);
$from = $mailHeader->fromaddress;
$subject = strip_tags($mailHeader->subject);
$date = $mailHeader->date;
The body of the email is then retrieved with a call to imap_body. Because our email script only displays plain text emails, we use strip_tags to remove all HTML formatting from the email:
$body = nl2br(strip_tags(imap_body($conn, $id)));
We then output all of these details to a form, including a button that lets us reply to this specific email:
As you can see, this form passes the value "reply" for the hidden form variable "what". The to, subject and message fields are also passed as hidden form variables, which in turn calls the ShowComposeForm function, which displays a HTML form in exactly the same was as the ShowEmail function.
Although this might sound a little confusing, the ShowComposeForm function is also used to compose a new email. The parameters passed to the function are the values for each text box in the form: if we don't pass any parameters then we're creating a new form. If we do, then we're replying to a message. Here's the function signature of ShowComposeForm:
function ShowComposeForm($to = "", $subject = "", $message = "")
The ShowComposeForm function includes a hidden form variable, what, which is set to "send", triggering a call to the SendMessage function when the form is submitted.
The function signature of SendMessage looks like this:
SendMessage($to, $subject, $message, $cc, $bcc);
SendMessage uses the imap_open function to connect to our mail server. If the connection was successful, it then uses imap_mail to send an email message to the intended recipient, like this:
One last function that I will mention is our DeleteEmails function. This function calls imap_delete as well as imap_explunge to remove email messages from our mailbox based on their ID. The ID's for the DeleteEmails function are passed as an array from the form generated by the ShowInbox function: