• Uncategorized
  • 0

Get emails from mailbox with PHP

With PHP it is very easy to send emails, as I have shown you in a recent article. With PHP you can do event more. It has functions to read mails directly from your mailbox. So it is possible to create automatic systems which are able to read messages from your inbox and react on them. You can for example start a process by sending a start command to your mailbox.


The Internet Message Access Protocol has more options to work with mails and mail boxes than other protocols like POP3. This is the reason why I choose for my example IMAP.

Create a connection to your mailbox

The following code shows how to connect with an existing IMAP mailbox:

For our connection we need a function called imap_open. This function needs some params which are:

  • server
    the first param is the server to which we want to establish the connection. This server hosts the IMAP mailbox. We need a domain name and a port. For IMAP the standard port is 143. It is possible that you need a different port. If the connection is SSL save than you may need 993.
  • username/loginname
    next param is your username or account name. Normally this is your mail address that you use to get your mails.
  • password
    you mailbox password.
  • optional params
    you can use some optional params here. For my example we only want to read mails so we set read only.

The result is a IMAP stream for your mailbox or false if something went wrong.

Get header and body of mails

You can use the IMAP steam to get header and body informations of all mails in mailbox. For this we can use PHP functions imap_headers and imap_fetchbody. This works for text mails and also HTML mails.

(Visited 1,393 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *