gmailexportfeaturesimg

Export Gmail Contacts in a CSV using PHP

Hello Friends,

In this blog post, I am going to let you know about how to export gmail contacts into a CSV file or Excel sheet or Excel file and use them for a different purpose.

It is hard to find the user on this planet who does not use the Google product like Gmail, Google drive and etc, even would have used at least one which might be Gmail.

Out of all Google product, Gmail is the most usable service used by millions of peoples across the world.

Gmail is a public email system which is used to send and receive the emails from one place to another place. Peoples use Gmail for their personal as well professional uses.

So if some time you need to export Gmail contacts in terms of email id as you decide them for email marketing purpose or something else then this application can be a great help which will help you in downloading all your Gmail contacts in a CSV file.

gmailexport12

 

we may require google contacts or email id for several purposes one of them could be sending the email campaign to all your Gmail contacts in one day which would not be feasible with Gmail as they have a daily limit for email sending.


So now the question is, how can you extract or export Gmail contacts using our application?

This would be really simple to develop this functionality to export gmail contacts from your gmail account. So before getting you to the mail coding part let me just introduce with some important aspects of this core functionality.

Before going to complex coding part just have a look at these basic terminology listed below.

While you will be developing this code product then you will encounter with one term again and again that is Google OAuth.


Now one question will arise in your mind that what is this google OAuth and how is it useful in order to export gmail contacts?

OAuth stands for “open standard for authorization” and provide a strong authorization scheme on behalf of owner, OAuth was started with oauth1.0

but it has been deprecated and replaced with oauth2.0, make sure you are using oauth2.0

OAuth Code: This token is only available with successful authorization and further we can request for an access token.

Access Token: Access token is just like a key which is used to access almost all APIS data.

Refresh Token: Often! we are confused with refresh the token. The refresh token is not a separate token even though it is same access token, but its value got refreshed after leaving one complete flow or log out from your session.

So Simply get the access token and make its session and maintain it till you get logout and at the time of re-login you will get a new access token or you can call it refresh token.

Steps for getting the google contacts or export Gmail Contacts: here we are explaining step-by-step process for accessing the google contacts.

our goal is to get three important things to make this code possible.

Client id, Client secret, and API key. To see the below procedure to obtain all these values.


First, copy and paste this link into the browser https://console.developers.google.com/project, this is a link to developer console.

Log in to your Google or Gmail account if you have not logged in yet.

gmailexport1


gmailexport2


gmailexport3


gmailexport4


gmailexport5


gmailexport6


gmailexport7


gmailexport8


gmailexport19


gmailexport10


gmailexport11


gmailexport131


Once you get your client id, client secret and API then you just need to create a project, here we are creating a project at NetBeans IDE. See the file structure below.
gmailexport14


index.php:

<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<title>Export Google Contacts Using PHP</title>
<meta name="robots" content="noindex, nofollow">

</head>
<body>

<div id="main" class="col-sm-6 col-md-4 col-lg-2">
<div id="envelope" class="col-sm-6 col-md-4 col-lg-2">

<header id="sign_in" class="col-sm-6 col-md-4 col-lg-2">
<center>
<h2>Export Gmail Contacts With Google Oauth PHP</h2>
</center>
</header>
<hr>
<div id="content" class="col-sm-6 col-md-4 col-lg-2">
<center>
<h3 id ="sign">Sign In with Google for retrieving Contacts</h3>
<div class="col-sm-6 col-md-4 col-lg-2">
<a href="https://accounts.google.com/o/oauth2/auth?client_id=<PASTE YOUR CLIENT ID>&redirect_uri=http://localhost/gmail_export/callback.php&scope=https://www.google.com/m8/feeds/&response_type=code"><img src="images/sign1.png" alt="" id="signimg"/></a>
</div>
</center>
</div>
</div>
</div>
</body>
</html>

style.css:

body {
margin:0;
padding:0;
font-family:raleway;
background-image: url(../images/repeat-bg.png);
}
#main{
width: 70%;
height: 100%;
margin-left: 30%;
margin-top: 5%;
position: relative;
}

h2{
font-family:raleway;
color: black;
}
div#envelope{
position: relative;
width: 60%;
border: 1px solid #CFCFD0;
border-radius: 10px;
background-color: #FFFFFF;

}
div#content{
width: 100%;

padding:12px auto;
overflow: hidden;
word-break: break-all;
overflow-wrap: break-word;
border-radius: 0 0 10px 10px;
background-color: #f7ecec;
}
header#sign_in{
font-family:raleway;
background-color: #4e562dc7;
text-align: center;
padding-top: 12px;
//padding-left: 5px;
padding-bottom: 15px;
margin-bottom: -8px;
border-radius: 10px 10px 0 0;
color: white;
}
header#info{
font-family:raleway;
background-color: #079BAE;
margin-top: -11px;
padding-top:15px;
padding-bottom: 42px;
padding-left: 15px;
padding-right: 15px;
font-size: 16px;
border-radius: 10px 10px 0 0;
color: white;

}
header#info a.user_name{
font-family:raleway;
text-decoration: none;
color:white;
}
div.logout{
padding-top: 30px;
float:right;
}
a.logout{
font-family:raleway;
font-size: 20px;
font-weight: 600;
text-decoration: none;
padding-right: 0 auto;
float:right;
color:white;
}
p {
padding: 0 25px;
}
p.profile {
font-weight: bold;
font-size: 20px;
}
img.user_img{
border-radius:50% 50% 50% 50%;
border:3px solid white;
}
p.welcome{
margin-top: -50px;
margin-left: 12%;
}
#sign{
//margin-left: 150px;
}
#signimg{
width:70%;

}
#logoutimg{

margin-left: 500px;
margin-bottom: 5px;
color: blue;
float: left;
position: relative;
margin-top: -35px;

}
#tbdata
{
border: 1px solid lightgrey;
margin-top: -20px;
font-family:raleway;
background-color: lightgray;
border: transparent;

}

#tb{
width :97.5%;
margin-left: 10px;
border: 1px solid gray;
box-shadow:#079BAE;

}
#btnimg
{
width:50px;
height: 50px;

color: blue;
position: absolute;
margin-bottom: -15px;
margin-left: -270px;

}

#name{
padding-right: 30px;
padding-left: 30px;
}

callback.php:

<?php
session_start();
?>
<?php
$accesstoken = '';
$client_id = '<PASTE YOUR CLIENT ID HERE>';
$client_secret = '<PASTE YOUR CLIENT SECRET HERE>';
$redirect_uri = 'http://localhost/gmail_export/callback.php';
$simple_api_key = '<PASTE YOUR API KEY HERE>';
$max_results = 500;
$auth_code = $_GET["code"];

function curl_file_get_contents($url) {
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect.

curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //To stop cURL from verifying the peer's certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}

$fields = array(
'code' => urlencode($auth_code),
'client_id' => urlencode($client_id),
'client_secret' => urlencode($client_secret),
'redirect_uri' => urlencode($redirect_uri),
'grant_type' => urlencode('authorization_code')
);
$post = '';
foreach ($fields as $key => $value) {
$post .= $key . '=' . $value . '&';
}
$post = rtrim($post, '&');

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($curl);

curl_close($curl);

$response = json_decode($result);
if (isset($response->access_token)) {
$accesstoken = $response->access_token;
$_SESSION['access_token'] = $response->access_token;
}

if (isset($_GET['code'])) {

$accesstoken = $_SESSION['access_token'];
}

if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}

$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=' . $max_results . '&oauth_token=' . $accesstoken;
$xmlresponse = curl_file_get_contents($url);

if ((strlen(stristr($xmlresponse, 'Authorization required')) > 0) && (strlen(stristr($xmlresponse, 'Error ')) > 0)) {
echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
exit();
}

//echo " <a href ='http://127.0.0.1/gmail_contact/callback.php?downloadcsv=1&code=4/eK2ugUwI_qiV1kE3fDa_92geg7s1DusDsN9BHzGrrTE# '><img src='images/excelimg.jpg' alt=''id ='downcsv'/></a>";
// echo "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005/Atom');

$result = $xml->xpath('//gd:email');

foreach ($result as $title) {
$arr[] = $title->attributes()->address;
echo $title->attributes()->displayName;
}
//print_r($arr);
foreach ($arr as $key) {
//echo $key."<br>";
}

$response_array = json_decode(json_encode($arr), true);

// echo "<pre>";
// print_r($response_array);
//echo "</pre>";

$email_list = '';
foreach ($response_array as $value2) {

$email_list = ($value2[0] . ",") . $email_list;
}

//echo $abc;
// $final_array[] = $abc;
// $farr =$final_array;
//echo "<pre>";
//print_r($final_array);
// echo "</pre>";
//<input type="text" value="<?php echo ($abc);?" name="email">
?>

<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="css/table.css" rel="stylesheet" type="text/css"/>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Export Google Contacts Using PHP</title>
<meta name="robots" content="noindex, nofollow">

</head>
<body>

<div id="main" >

<div class="col-sm-6 col-md-4 col-lg-2">
<div id="envelope" class="col-sm-6 col-md-4 col-lg-2">

<header id="sign_in">
<h2> <form action='csvdownload.php' method='post'>
<input type='text' value= '<?php echo $email_list; ?>' name='email' style='display: none'>

<input type='image' width='100' value='submit' src='images/excelimg1.gif' alt='submit Button' id ='btnimg'>
</form>Export Gmail Contacts<a href='https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost/gmail_export/index.php' ><img src='images/logoutimg1.png' alt=''id ='logoutimg'/></a></h2>
</header>
<hr>
<div id="content" class="col-sm-6 col-md-4 col-lg-2">
<div class="col-sm-6 col-md-4 col-lg-2">

<div class="col-sm-6 col-md-4 col-lg-2">

<table cellspacing='0'>
<thead>
<td id="name">S.No</td>
<td>Email Addresses</td>
</thead>
<?php
$count = 0;
foreach ($result as $title) {
?>
<tr>
<td><?php echo $count;
$count++ ?></td>
<link href="style.css" rel="stylesheet" type="text/css"/>
<td><?php echo $title->attributes()->address; ?></td>
</tr>
<?php
}
?>

</table>

</div>

</div>
</div>
</div>
</div>
</div>

</body></html>

csvdownload.php:

<?php

$data = $_POST['email'];

$arry[] = explode(',', $data);

foreach ($arry as $row) {
$arlength = count($row);
for ($i = 0; $i < $arlength; $i++) {
$farry[] = explode(',', $row[$i]);
}
}

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$file = fopen('php://output', 'w');
fputcsv($file, array('Email'));
foreach ($farry as $row) {
fputcsv($file, $row);
}
exit();

table.css:

table a:link {
color: #666;
font-weight: bold;
text-decoration:none;
}
table a:visited {
color: #999999;
font-weight:bold;
text-decoration:none;
}
table a:active,
table a:hover {
color: #bd5a35;
text-decoration:underline;
}
table {
font-family: 'Raleway', sans-serif;
//color:#666;
font-size:12px;
text-shadow: 1px 1px 0px #fff;
background:#eaebec;
//margin:20px;
border:#ccc 1px solid;
font-size: 16px;
-moz-border-radius:3px;
-webkit-border-radius:3px;
border-radius:3px;

-moz-box-shadow: 0 1px 2px #d1d1d1;
-webkit-box-shadow: 0 1px 2px #d1d1d1;
box-shadow: 0 1px 2px #d1d1d1;
margin: 50px 50px;
width: 85%;

}
table th {
padding:21px 25px 22px 25px;
border-top:1px solid #fafafa;
border-bottom:1px solid #e0e0e0;

background: #ededed;
background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
background: -moz-linear-gradient(top, #ededed, #ebebeb);
}
table th:first-child {
text-indent: center;
padding-left:20px;
}
table tr:first-child th:first-child {
-moz-border-radius-topleft:3px;
-webkit-border-top-left-radius:3px;
border-top-left-radius:3px;
}
table tr:first-child th:last-child {
-moz-border-radius-topright:3px;
-webkit-border-top-right-radius:3px;
border-top-right-radius:3px;
}
table tr {
text-indent: center;
padding-left:20px;
}
table td:first-child {
text-align: center;
padding-left:20px;
border-left: 0;
}
table td {
padding:18px;
border-top: 1px solid #ffffff;
border-bottom:1px solid #e0e0e0;
border-left: 1px solid #e0e0e0;

background: #fafafa;
background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
background: -moz-linear-gradient(top, #fbfbfb, #fafafa);
}
table tr.even td {
background: #f6f6f6;
background: -webkit-gradient(linear, left top, left bottom, from(#f8f8f8), to(#f6f6f6));
background: -moz-linear-gradient(top, #f8f8f8, #f6f6f6);
}
table tr:last-child td {
//border-bottom:0;
}
table tr:last-child td:first-child {
-moz-border-radius-bottomleft:3px;
-webkit-border-bottom-left-radius:3px;
border-bottom-left-radius:3px;
}
table tr:last-child td:last-child {
-moz-border-radius-bottomright:3px;
-webkit-border-bottom-right-radius:3px;
border-bottom-right-radius:3px;
}
table tr:hover td {
background: #f2f2f2;
background: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#f0f0f0));
background: -moz-linear-gradient(top, #f2f2f2, #f0f0f0);
}

contact.css:

@import url(http://fonts.googleapis.com/css?family=Raleway);

h1{
text-align:center;
//color: black;
font-size: 2em;
}

#main{
margin: -150px 100px;
font-family: 'Raleway', sans-serif;
}

h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -58px -40px;
padding: 40px 40px;
color: black;
font-weight: bolder;
font-size: 1.5em;
margin-bottom: -67px;
}

hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
}

#login{
width:580px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 0px 40px 0px;
//margin-top: 70px;
//margin: 50px;
margin: 15px 345px;
}

input[type=text],input[type=email],input[type=password]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}

textarea{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
margin-bottom: 5px;
font-size: 16px;
font-family:raleway;
}

input[type=submit]{
width: 40%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 12px;
}

h3{
text-align: center;
font-weight: bold;
}

table{
width: 100%;
text-align: center;
}

thead{
font-weight: bold;
}

#contab td{
border: 1px solid black;
}

#download{
float: left;
margin-top: 7px;
}

#logout{
float: right;
margin-top: -31px;
margin-right: -14px;
}

a{
text-decoration: none;
font-weight: bold;
}

img{
// margin-top: -60px;
}

h2 span {
margin-left: -67px;
}

In a case of any queries, you can write us at a5theorys@gmail.com we will get back to you ASAP.

Hope! you would have enjoyed this post to export gmail contacts in a CSV file.

Please feel free to give your important feedbacks in the comment section below.

Have a great time! Sayonara!