Php imap get from

How to get emails using PHP and IMAP ?

Reading emails from the Gmail account using PHP will be an enriching task for web developers for its simplicity of code through IMAP (Internet Message Access Protocol). Sometimes there can be a requirement in web projects or from a client that needs the complete management of inbox emails or access to email contents from his Gmail account. This feature can also be useful in email marketing or email newsletters that will be sent automatically on a particular schedule. So while researching Gmail account access, one should try listing emails from the Gmail account using PHP and its IMAP functions extension.

IMAP is an internet standard protocol used by clients to get emails from a mail server over a TCP/IP connection with SSL security. The IMAP extension available in PHP libraries provides efficient processing of its email structure and access to email messages via communicating with the email servers.
We use PHP code to connect to the Gmail server and use standard IMAP functions to open up the Gmail account and access or fetch emails based on certain criteria.

Basic requirements: The following are needed for the development of the functionality.

  1. PHP5 or latest PHP version.
  2. Enable the IMAP Extension in PHP installation.
  3. In Gmail account settings, IMAP should be enabled.

Steps to Enable IMAP in XAMPP:

  1. Go to php.ini configuration file
  2. Search for “;extension=php_imap.dll”
  3. Remove the beginning of semicolon and it should be “extension=php_imap.dll”
  4. Also edit max_execution_time = 4000

Steps to Enable IMAP in Gmail Account:

  1. Open Gmail.
  2. Click Settings.
  3. Select the Forwarding and POP/IMAP blue tab.
  4. Select “IMAP Access:” section and Enable IMAP radio button.
  5. Click Save Changes.
  6. Don’t forget to turn on access for less secure apps for Gmail account.

Note: For normal applications, an IMAP server listens on 143 port number.

PHP Code: The following is the HTML and PHP code to list emails from Gmail account. To connect to Gmail, the developer needs the individual’s “username” and “password” to be set in the code. Once connected, we search for all emails or emails based on certain criteria by using the imap_search() function. The emails are sorted in a reverse manner so that the latest mails are available on the top using the PHP rsort() function. This PHP function sorts an array in descending order. For every email returned, the subject, from, partial content, and date-time messages are captured. The imap_fetchbody() function fetches a particular section of the email body. So to get the plain text part of the email, we can use “1.1” option as the third parameter.

Читайте также:  Python alpine docker image

Источник

Query

Based on your configuration you can either receive a specific message by providing a message number (if your fetch option is set to ST_MSGN) or providing a uid.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Message $message */ $message = $query->getMessage($id = 1);

Get a specific message by its uid

You can fetch a specific message by its uid even if you are having the fetch option set to ST_MSGN.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Message $message */ $message = $query->getMessageByUid($uid = 1);

Get a specific message by its message number

You can fetch a specific message by its message number even if you are having the fetch option set to ST_UID.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Message $message */ $message = $query->getMessageByMsgn($msgn = 1);

Get all messages

Get a collection of all available messages.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->all()->get();

Get all messages in chunks

Fetch all available messages in chunks to reduce the request / response size per «transaction». This method may also lead to more request overall, so you might have to be careful with raitlimits.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ $query->all()->chunked(function($messages, $chunk)< /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ dump("chunk #$chunk"); $messages->each(function($message)< /** @var \Webklex\PHPIMAP\Message $message */ dump($message->uid); >); >, $chunk_size = 10, $start_chunk = 1);

Flag all fetched messages as read

You can automatically flag all fetched messages as «seen».

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ $query->markAsRead();

Don’t flag all fetched messages as read

You can prevent the server from automatically flagging all fetched messages as «seen».

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ $query->leaveUnread();

Don’t fetch the message body

If your script takes for ever to complete, or if you don’t need the body, you can prevent the body fetching.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ $query->setFetchBody(false);

Limit the result

Limit the result to a specific limit and / or page. This has a great positive effect on your execution time.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->all()->limit($limit = 10, $page = 2)->get();

In this case you would limit the result to 10, but since $page is set to 2, the first 10 results will be skipped and the next 10 will be returned.

Count the result

Count the amount of available messages without fetching them.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var integer $count */ $count = $query->all()->count();

Get a paginated result

Get a paginated collection of all available messages. Here is a pagination example.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */ $paginator = $query->all()->paginate($per_page = 5, $page = null, $page_name = 'imap_page');

Set the sort order

You can define the way the fetched messages should be ordered. Use «asc» for ascending and «desc» to order descending.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var integer $count */ $query->setFetchOrder("asc"); $query->setFetchOrderAsc(); $query->fetchOrderAsc(); $query->setFetchOrder("desc"); $query->setFetchOrderDesc(); $query->fetchOrderDesc();

Enable Soft fail

Enable the «soft fail» mode if you want to ignore certain exception while fetching bulk messages.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ /** @var [integer]\Exception $errors */ $messages = $query->all()->softFail()->get(); $errors = $query->errors();

Get all messages from a specific sender

Get a collection of all available messages from a specific sender. In this case «example@domain.com».

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->from('example@domain.com')->get();

Get all messages since a specific date

Get a collection of all available messages which were sent after after a given date. The IMAP protocol does not allow to search for datetime keywords.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->since('15.03.2018')->get(); $messages = $query->since(\Carbon\Carbon::now()->subDays(5))->get();

Get all messages containing a specific text

Get a collection of all available messages containing a specific text.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->text('hello world')->get();

Alternative method names

Every search criteria can be added using several different naming schemes. Here is an example for Query::text() .

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->text('hello world')->get(); $messages = $query->Text('hello world')->get(); $messages = $query->whereText('hello world')->get(); $messages = $query->where([['TEXT', 'Hello world']])->get();

Search by excluding

You can also search for messages which do not match the criteria. Like a negative search criteria. In this example, all messages which do not contain the text «hello world».

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->notText('hello world')->get(); $messages = $query->not_text('hello world')->get(); $messages = $query->not()->text('hello world')->get();

Chained search criteria

You might want to search for all messages from a certain sender, which are also unseen and have to contain a specific text.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->from('example@domain.com')->unseen()->text('hello world')->get();

Custom search criteria

Your provider supports custom search criteria? Great! Here is an example where the criteria «FOOBAR» is available and consumes a string.

/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */ $messages = $query->where([["CUSTOM_FOOBAR" => "fooBar"]])->get();

All available search criteria

  • ALL — return all messages matching the rest of the criteria
  • ANSWERED — match messages with the \ANSWERED flag set
  • BCC «string» — match messages with «string» in the Bcc: field
  • BEFORE «date» — match messages with Date: before «date»
  • BODY «string» — match messages with «string» in the body of the message
  • CC «string» — match messages with «string» in the Cc: field
  • DELETED — match deleted messages
  • FLAGGED — match messages with the \FLAGGED (sometimes referred to as Important or Urgent) flag set
  • FROM «string» — match messages with «string» in the From: field
  • KEYWORD «string» — match messages with «string» as a keyword
  • NEW — match new messages
  • NOT — not matching
  • OLD — match old messages
  • ON «date» — match messages with Date: matching «date»
  • RECENT — match messages with the \RECENT flag set
  • SEEN — match messages that have been read (the \SEEN flag is set)
  • SINCE «date» — match messages with Date: after «date»
  • SUBJECT «string» — match messages with «string» in the Subject:
  • TEXT «string» — match messages with text «string»
  • TO «string» — match messages with «string» in the To:
  • UNANSWERED — match messages that have not been answered
  • UNDELETED — match messages that are not deleted
  • UNFLAGGED — match messages that are not flagged
  • UNKEYWORD «string» — match messages that do not have the keyword «string»
  • UNSEEN — match messages which have not been read yet
Читайте также:  Css input type text name

Источник

Retrieve Your Gmail Emails Using PHP and IMAP

Gmail

Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time! Just for fun, I’ll be using the MooTools Fx.Accordion plugin to display each email.

The CSS

div.toggler < border:1px solid #ccc; background:url(gmail2.jpg) 10px 12px #eee no-repeat; cursor:pointer; padding:10px 32px; >div.toggler .subject < font-weight:bold; >div.read < color:#666; >div.toggler .from, div.toggler .date < font-style:italic; font-size:11px; >div.body

Some simple CSS formatting.

The MooTools JavaScript

window.addEvent('domready',function() < var togglers = $$('div.toggler'); if(togglers.length) var gmail = new Fx.Accordion(togglers,$$('div.body')); togglers.addEvent('click',function() < this.addClass('read').removeClass('unread'); >); togglers[0].fireEvent('click'); //first one starts out read >);

Some simple accordion code.

The PHP

/* connect to gmail */ $hostname = 'INBOX'; $username = 'davidwalshblog@gmail.com'; $password = 'davidwalsh'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error()); /* grab emails */ $emails = imap_search($inbox,'ALL'); /* if emails are returned, cycle through each. */ if($emails) < /* begin output var */ $output = ''; /* put the newest emails on top */ rsort($emails); /* for every email. */ foreach($emails as $email_number) < /* get information specific to this email */ $overview = imap_fetch_overview($inbox,$email_number,0); $message = imap_fetchbody($inbox,$email_number,2); /* output the email header information */ $output.= '
'; $output.= ''.$overview[0]->subject.' '; $output.= ''.$overview[0]->from.''; $output.= 'on '.$overview[0]->date.''; $output.= '
'; /* output the email body */ $output.= '
'.$message.'
'; > echo $output; > /* close the connection */ imap_close($inbox);

With our individual username/password settings set, we connect to Gmail. Once connected, we request all emails. If we find emails, I reverse sort the emails so that the newest emails appear on top. For every email we receive, I output the subject and message in MooTools Fx.Accordion format.

Читайте также:  Javascript ajax асинхронный запрос

Now that I’ve shown you the basics, it’s time for you to build your next great PHP email app! Go ahead and send a few emails to davidwalshblog@gmail.com to see your eamil display on the page!

There are some encoding issues and I’ve not found a great way to include images. Any tips appreciated!

Источник

Оцените статью