PHP imap gmail email
Objective of this tutorial
- Understanding IMAP
- Install imap on ubuntu os
- Connect to gmail box using imap php
- Fetch emails from gmail
- Get email body and print
- Close connection
Understanding IMAP
In computing, the Internet Message Access Protocol (IMAP) is an Internet standard protocol used by e-mail clients to retrieve e-mail messages from a mail server over a TCP/IP connection. IMAP is defined by RFC 3501.
Install imap on ubuntu os
On Ubuntu Linux this installs the PHP5-IMAP module:
apt-get install php5-imap
On CentOS and other Unix Operating Systems this installs it:
yum install php-imap
Enable module
php5enmod imap
restarting the server:
service httpd restart
Gmail less secure apps
Many times gmail does not allow localhost or less secure code.
So allow this conflict you have to tell to gmail about allow less secure apps.
Please follow this link
https://support.google.com/accounts/answer/6010255?hl=en
Enable imap in gmail account
If you want to read gmail’s email from imap protocol you have to enable imap setting from your gmail account.
Please read this article : How to enable imap gmail
https://support.google.com/mail/answer/7126229?hl=en
Connect to gmail box using imap php
Create a simple file mail.php or whatever you like:
and write following code
<?php set_time_limit(-1); /* connect to gmail */ $hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX'; $username = 'youremailaddress@gmail.com'; $password = 'your!@#password'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
Fetch emails from gmail
Continue…
/* grab emails */ $mails = imap_search($inbox,'ALL'); /* You can set your search criteria see reference here http://php.net/manual/en/function.imap-search.php */ /* if emails are returned, cycle through each... */ if($mails) { /* put the newest emails on top */ rsort($mails); $html = ''; foreach($mails as $email_number) { /* get information specific to this email */ $overview = imap_fetch_overview($inbox,$email_number,0); $message = imap_fetchbody($inbox,$email_number,1); /* output the email header information */ $html.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">'; $html.= '<span class="subject">'.$overview[0]->subject.'</span> '; $html.= '<span class="from">'.$overview[0]->from.'</span>'; $html.= '<span class="date">on '.$overview[0]->date.'</span>'; $html.= '</div>'; /* output the email body */ $html.= '<div class="body">'.$message.'</div>'; }
Get emails and print body
Continue..
/* Print email body */ echo $html; } /* Close imap connection */ imap_close($inbox);
For additional resource and reference please read official php imap book
http://php.net/manual/en/book.imap.php
PHP imap gmail email
Contact for PHP Mysql, Codeigniter, Laravel, symfony, NodeJS, AngularJS, ReactJS training in mumbai.
Weekend Classes available.
Call me on 9022349606.
Team Webrocom.