PHP IMAP

From DreamHost

Jump to: navigation, search

Contents

Introduction

Depending on your server(s)' PHP and email installation, you may use IMAP protocol functions for more advanced email control, including saving sent emails and checking your inbox for new messages.

Verify PHP INI Settings

Before using IMAP functions, check your custom PHP INI file, or phpinfo() function, to make sure your PHP version is compiled/installed '--with-imap'.

Basic 'mail()' Function Replacement

imap_mail() function can replace the standard mail() function typically used for sending email. Parameters for both functions are mostly similar. A basic example using imap_mail():

<?php

$to = "recipient@example.com, someotherguy@example.com";
$subject = "Test Email";
$body = "This is only a test.";
$headers = "From: me@example.com\r\n".
    	"Reply-To: me@example.com\r\n";
$cc = null;
$bcc = null;
$return_path = "me@example.com";

imap_mail($to, $subject, $body, $headers, $cc, $bcc, $return_path);

?>

Saving Sent Emails

In the following example, we save the above message in our Sent folder, since email functions don't automatically do so:


<?php

// connect to your Inbox through port 143.  See imap_open() function for more details
$mbox = imap_open("{mail.example.com:143/notls}INBOX", "me@example.com", "password");


// save the sent email to your Sent folder by just passing a string composed 
// of the entire message + headers.  See imap_append() function for more details.
// Notice the 'r' format for the date function, which formats the date correctly for messaging.

imap_append($mbox, "{mail.example.com:143/notls}INBOX.Sent",
     "From: me@example.com\r\n".
     "To: ".$to."\r\n".
     "Subject: ".$subject."\r\n".
     "Date: ".date("r", strtotime("now"))."\r\n".
     "\r\n".
     $body.
     "\r\n"
     );

// close mail connection.
imap_close($mbox);

?>

External Links

Personal tools