Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get email from gmail with PHP IMAP
<?php
error_reporting(0);
$mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";
$username = "your@gmail.com";
$password = "***";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>IMAP mailbox - KANG^CAHYA</title>
<!-- Custom style -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
<style>
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
background-color: #FFFFFF;
}
</style>
</head>
<body>
<div class="container">
<h1 class="page-header"><?=$username;?></h1>
<?php
$read = imap_open($mailbox, $username, $password) or die('<div class="alert alert-danger alert-dismissable">Cannot connect to gmail.com: ' . imap_last_error().'</div>');
$search = 'SINCE "' . date("j F Y", strtotime("-1 years")) . '"';
$array = imap_search($read, $search);
if($array)
{
$html = '';
rsort($array);
foreach($array as $result)
{
$overview = imap_fetch_overview($read,$result,0)[0];
$message = imap_fetchbody($read,$result,1, FT_PEEK);
$reply = imap_headerinfo($read,$result,0);
$html.= '
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">
<span class="subject">'.strip_tags($overview->subject).'</span>
<span class="from">'.$overview->from.'</span>
<span class="date">on '.$overview->date.'</span>
</h4>
</div>
<div class="panel-body">
<pre>'. (base64_decode($message, true) ? base64_decode($message) : $message).'
<hr>From: '.$reply->from[0]->mailbox.'@'.$reply->from[0]->host.'</pre>
</div>
</div>
';
}
echo $html;
}
imap_close($read);
?>
</div>
<!-- Javascript -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.