PHP - Connect mailbox office 365 with OAuth - php

Please forgive my amateurism both in php and on stackoverflow.
I have a PHP script that reads emails from an office 365 mailbox, for this I use a standard connection:
$Inbox = imap_open('{Outlook.office365.com:993/imap/ssl}', 'mabal#mydomain.com', 'mypassword');
Then to read the new emails received, I used the command:
$UnRead = imap_search($Inbox, 'UNSEEN');
Starting 20221001 - October 1, 2022, Microsoft will remove this authentication and require OAuth2 authentication.
I registered my web application at Microsoft Azure and tried several settings. I have done a lot of research that allows me to connect to the mailbox to be able to read the mails without going through an interaction with a user. I've found nothing.
Does anyone have a step-by-step solution to retrieve a variable bound to an "imap_open" or do you have to use a completely different system.
Thanks for your help.

It's been a wild ride for me and my coworkers but we found a solution.
1 - Configure your mail box in Azure
(I didn't do this part so i can't help you more than that ! )
Edit : Thanks to parampal-pooni, this link explains how to configurate in azure.
You will need :
The client Id
The tenant Id
The secret client
The redirect Uri (Set it to http://localhost/test_imap)
2 - Grab a code to get a token
Construct this url :
$TENANT="5-48...";
$CLIENT_ID="c-9c-....";
$SCOPE="https://outlook.office365.com/IMAP.AccessAsUser.All";
$REDIRECT_URI="http://localhost/test_imap";
$authUri = 'https://login.microsoftonline.com/' . $TENANT
. '/oauth2/v2.0/authorize?client_id=' . $CLIENT_ID
. '&scope=' . $SCOPE
. '&redirect_uri=' . urlencode($REDIRECT_URI)
. '&response_type=code'
. '&approval_prompt=auto';
echo($authUri);
Go to the link, connect to the mail box with the passeword.
Once it done, you will be redirect to : http://localhost/test_imap?code=LmpxSnTw...&session_state=b5d713....
Save the code (remove the '&' at the end !) and the session state inside the url.
These codes expired after a few hours !
3 - Get an access token
$CLIENT_ID="c-9c-....";
$CLIENT_SECRET="Y~tN...";
$TENANT="5-48...";
$SCOPE="https://outlook.office365.com/IMAP.AccessAsUser.All offline_access";
$CODE="LmpxSnTw...";
$SESSION="b5d713...";
$REDIRECT_URI="http://localhost/test_imap";
echo "Trying to authenticate the session..";
$url= "https://login.microsoftonline.com/$TENANT/oauth2/v2.0/token";
$param_post_curl = [
'client_id'=>$CLIENT_ID,
'scope'=>$SCOPE,
'code'=>$CODE,
'session_state'=>$SESSION,
'client_secret'=>$CLIENT_SECRET,
'redirect_uri'=>$REDIRECT_URI,
'grant_type'=>'authorization_code' ];
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($param_post_curl));
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$oResult=curl_exec($ch);
echo "result : \n";
var_dump($oResult);
The access_token given in response is going to work only for a few hours. ( If your script is going to be launch on a daily basic you need to recreate a token. I'm going to show you how in the part 5 ! Save the refresh_token inside $oResult. If you don't have the "refresh_token" you have forgot to put "offline_access" in the scope)
Edit : I forgot to add the redirect_uri in this step, thank jose ayram
4 - Connect to the mail box
Now choose your favorite library ;) ! We will use webklex/php-imap for this example (https://github.com/Webklex/php-imap)
include __DIR__.'/vendor/autoload.php';
use Webklex\PHPIMAP\ClientManager;
$access_token="EH.j8s5z8...";
//$cm = new ClientManager($options = ["options" => ["debug" => true]]);
$cm = new ClientManager();
$client = $cm->make([
'host' => 'outlook.office365.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => false,
'username' => 'mymailbox#domain.com',
'password' => $access_token,
'protocol' => 'imap',
'authentication' => "oauth"
]);
try {
//Connect to the IMAP Server
$client->connect();
$folder = $client->getFolder('INBOX');
$all_messages = $folder->query()->all()->get();
//DONE ! :D
} catch (Exception $e) {
echo 'Exception : ', $e->getMessage(), "\n";
}
5 - Connecting to the mail box everyday
include __DIR__.'/vendor/autoload.php';
use Webklex\PHPIMAP\ClientManager;
$CLIENT_ID="c-9c-....";
$CLIENT_SECRET="Y~tN...";
$TENANT="5-48...";
$REFRESH_TOKEN="EebH9H8S7...";
$url= "https://login.microsoftonline.com/$TENANT/oauth2/v2.0/token";
$param_post_curl = [
'client_id'=>$CLIENT_ID,
'client_secret'=>$CLIENT_SECRET,
'refresh_token'=>$REFRESH_TOKEN,
'grant_type'=>'refresh_token' ];
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($param_post_curl));
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//ONLY USE CURLOPT_SSL_VERIFYPEER AT FALSE IF YOU ARE IN LOCALHOST !!!
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);// NOT IN LOCALHOST ? ERASE IT !
$oResult=curl_exec($ch);
echo("Trying to get the token.... \n");
if(!empty($oResult)){
echo("Connecting to the mail box... \n");
//The token is a JSON object
$array_php_resul = json_decode($oResult,true);
if( isset($array_php_resul["access_token"]) ){
$access_token = $array_php_resul["access_token"];
//$cm = new ClientManager($options = ["options" => ["debug" => true]]);
$cm = new ClientManager();
$client = $cm->make([
'host' => 'outlook.office365.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => false,
'username' => 'mymailbox#domain.com',
'password' => $access_token,
'protocol' => 'imap',
'authentication' => "oauth"
]);
try {
//Connect to the IMAP Server
$client->connect();
}catch (Exception $e) {
echo 'Exception : ', $e->getMessage(), "\n";
}
}else{
echo('Error : '.$array_php_resul["error_description"]);
}
}
I hope it will help you.

Execute this curl
Replace client_id, client_secret and tenant_id
In scope you can try to use https://outlook.office365.com/.default, https://graph.microsoft.com/.default or https://outlook.office.com/.default
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id={CLIENT_ID}&scope=https%3A%2F%2Foutlook.office365.com%2F.default&client_secret={CLIENT_SECRET}&grant_type=client_credentials' 'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
PHP-imap login
<?php
// ....
$instance = new ClientManager();
$this->client = $instance->make([
'host' => "outlook.office365.com",
'port' => "993",
'encryption' => 'ssl',
'validate_cert' => true,
'username' => "email#outlook.com",
'password' => $curlAcessToken, // Access token curl
'protocol' => 'imap',
'authentication' => "oauth",
]);

Related

Curl GET Request to the spotify Authorization API

I need some help with my Curl GET Request to the Spotify API.
The API has three different ways/endpoints to get an authorization.
I read some articles, to find the correct syntax to send the request. But i always get an error. If i post the url into my brwoser it works perfectly, also with the redirect uri.
But it doesnt work with the Curl GET Request.
It sounds stupid, but i spend the last three days with this Problem.
My code:
<?php
$client_id = 'myClientID';
$redirect_url = 'http://mywebsite/first/page.php';
$scope = 'user-read-private%20user-read-email';
$data = array(
'client_id' => $client_id,
'response_type' => 'code',
'redirect_uri' => $redirect_url,
'state' => stateHash(), // Create a random hash
'scope' => $scope,
'show_dialog' => 'true'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/authorize' . http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
$result=curl_exec($ch);
echo $result;
The error from the API Shows me this:
or i got an "1" as response.
I hope that i get some nice tips :)
There is a package for Spotify web API try using that
composer require jwilsson/spotify-web-api-php
Before using the Spotify Web API, you'll need to create an app at Spotify’s developer site.
Simple example displaying a user's profile:
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
}
For more instructions and examples, check out the documentation.

Not able to post with PHP Twitter API

I am using TwitterAPIExchange to publish tweets to Twitter. Over the last 4 months I had no problems until I switched from HTTP to HTTPS.
I did not think this would be a problem as I do not even see this as a setting within the Developers APP and I am doing all this through crontab.
I am using the identical code below on two different servers and the one with SSL I get a successful connection (no errors) but no posting of the tweet -- meanwhile on the server without SSL I get a successful connection and a successful post.
Can a IP get blocked and if so, how do I check it if is, or is SSL a problem -- what do I need to do to fix this?
require_once('TwitterAPIExchange.php');
$connection = array('oauth_access_token' => 'xxx', 'oauth_access_token_secret' => 'xxx', 'consumer_key' => 'xxx', 'consumer_secret' => 'xxx');
try {
$twitter = new TwitterAPIExchange($connection);
echo 'Connection success <br /> ';
$response = $twitter->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')->setPostfields(array('status' => 'Test Tweet'))->performRequest();
$json = json_decode($response, true);
if (!empty($json['id_str'])) echo 'Post success: '.$json['id_str'];
}
catch (Exception $ex) {
echo $ex->getMessage();
}
Added CURLOPT_SSL_VERIFYPEER => false to TwitterAPIExchange

Google Admin SDK: You are not authorized to access this API

Since the Google Login Auth is disabled since last week I'm trying to get oAuth 2.0 working with a service account. We want to give users on our internal web application the oppurtunity to set there Out of Office.
I downloaded the lastest Google APIs Client Library for PHP. In the Google Developer Console, I have created a new project for my application and created a Service account credentials. I have also enabled the API service: Admin SDK in the Developer Console.
I have granted the account user ID access to the correct scopes (I think):
When I use the service-account.php example and change the details, I recieve an JSON with an access token, but when I do an CURL request (same as before) to get the e-mail settings from a user, the error "You are not authorized to access this API." occur.
My code:
<?php
include_once "templates/base.php";
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_id = '124331845-DELETEDPART-hbh89pbgl20citf6ko.apps.googleusercontent.com'; //Client ID
$service_account_name = '124331845-DELETEDPART-89pbgl20citf6ko#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'globaltext-4ce09b20cb73.p12'; //key.p12
$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://apps-apis.google.com/a/feeds/emailsettings/2.0/'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$aOutput = json_decode($client->getAccessToken());
$strEmailAdresSplit = explode('#', "FIRSTNAME.LASTNAME#DOMAIN.EXTENSION");
$strDomein = $strEmailAdresSplit[1];
$strAlias = $strEmailAdresSplit[0];
$resConnectionJobs = curl_init();
$aHeader = array();
$aHeader[] = 'Authorization: Bearer '.$aOutput->access_token;
$aHeader[] = 'Content-Type: application/atom+xml';
curl_setopt($resConnectionJobs, CURLOPT_URL, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/DOMAIN.EXTENSION/FIRSTNAME.LASTNAME/vacation");
curl_setopt($resConnectionJobs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($resConnectionJobs, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($resConnectionJobs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($resConnectionJobs, CURLOPT_HEADER, false);
$oCurlData = curl_exec($resConnectionJobs);
curl_close($resConnectionJobs);
echo $oCurlData;
?>
Are you certain your credentials are OK?
Please try the following procedure to make sure you have the right credentials.
Creating your API keys
Go to the developer's console and follow these steps:
Select your project
Choose menu item "APIs & auth"
Choose menu item "Registered app"
Register an app of type "web application"
Choose one of the following options, depending on what kind of app you're creating. Server side languages should use this option :
Key for server apps (with IP locking)
Getting access token & refresh token
Create a file that contains the following code :
<?php
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
$params = array(
"code" => $code,
"client_id" => YOUR_CLIENT_ID,
"client_secret" => YOUR_CLIENT_SECRET,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => YOUR_CLIENT_ID,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/plus.me"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
Now, replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your client ID and client secret.
Make sure your scope is correct. For example, it should be https://www.googleapis.com/auth/analytics if you want to get access to Analytics.
If you run the file, you should get an OAuth2 approval screen.
If you now press Accept, you should get a result that looks like this:
{
"access_token" : YOUR_ACCESS_TOKEN,
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : YOUR_REFRESH_TOKEN
}
The result may contain additional fields, depending on which scope you're applying for.
Connecting with Google's systems in background
Once you get the above to work, your application needs to implement the following workflow:
1) Check if your input contains a GET parameter named "code". If "code" is present, get a new access token and repeat this step (refresh your page)
If "code" is not present, go to step 2.
2) Check if you have credentials stored for your service. If credentials are present, check if your access token has expired or will expire soon. Then go to step 3. If credentials are not present, go to the auth path of your service to get the auth code and go back to step 1 (make sure Google redirects to your current URL).
3) If refresh is needed, refresh your page and go back to step 1.
If refresh is not needed, you're ready to actually do what you wanted to do in the first place.
Google's PHP library takes care if the oAuth2 flow for you, however. If you're using their library, each of the steps in the 3-step process are taken care of by the library and you should just be able to do whatever you want to do with Google's services straight away. I use this strategy myself in my Google Adwords dashboard.
You can, however, just write your custom library and connect with the service directly. Herebelow is some dev code from a project I wrote a few months ago. While it doesn't work out of the box (since it's a controller that's part of a larger application), it should help you understand the flow that Google's library takes care of under the hood.
namespace Application;
class Controller_API_Google_Youtube extends Controller_API {
public function read() {
$scope = "https://www.googleapis.com/auth/youtube";
$this->doOauth($scope);
}
function doOauth($scope) {
$oauth2Credentials = JSON_File::load(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json');
$paths = array(
'token' => 'https://accounts.google.com/o/oauth2/token',
'auth' => "https://accounts.google.com/o/oauth2/auth"
);
$refreshtime = 300;
if (isset($_GET['code'])) {
// Get access code
$query = $_GET;
unset($query['code']);
if (count($query) > 0) {
$query = '?' . http_build_query($query);
} else {
$query = '';
}
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'url' => $paths['token'],
'returntransfer' => 1,
'post' => true,
'postfields' => array(
'code' => $_GET['code'],
"client_id" => $oauth2Credentials['client_id'],
"client_secret" => $oauth2Credentials['client_secret'],
"redirect_uri" => HTTP_PROTOCOL . URL_PATH . $query,
"grant_type" => "authorization_code"
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$info = $response['maps']->getInfo();
$content = $response['maps']->getContent();
if ($info['http_code'] === 200) {
$output = JSON::decode($content);
$oauth2Credentials[$scope] = array();
$oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
$oauth2Credentials[$scope]['access_token'] = $output['access_token'];
$oauth2Credentials[$scope]['refresh_token'] = $output['refresh_token'];
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
header("Location: " . HTTP_PROTOCOL . URL_PATH . $query);
} else {
echo "Something went wrong";
}
} elseif (!isset($oauth2Credentials[$scope])) {
// Get auth code
header("Location: " . $paths['auth'] . '?' . http_build_query(
array(
"response_type" => "code",
"client_id" => $oauth2Credentials['client_id'],
"redirect_uri" => HTTP_PROTOCOL . DOMAIN_PATH,
"scope" => $scope
)
));
} elseif ($oauth2Credentials[$scope]['expires'] - $refreshtime < time()) {
// Refresh access code
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'url' => $paths['token'],
'returntransfer' => 1,
'post' => true,
'postfields' => array(
"client_id" => $oauth2Credentials['client_id'],
"client_secret" => $oauth2Credentials['client_secret'],
"refresh_token" => $oauth2Credentials[$scope]['refresh_token'],
"grant_type" => "refresh_token"
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$info = $response['maps']->getInfo();
$content = $response['maps']->getContent();
if ($info['http_code'] === 200) {
$output = JSON::decode($response['maps']->getContent());
$oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
$oauth2Credentials[$scope]['access_token'] = $output['access_token'];
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
$this->read();
} else {
$this->output = array("error" => "Something went wrong");
}
} else {
$this->doSomethinguseful($oauth2Credentials, $scope);
}
return $this;
}
function doSomethinguseful($oauth2Credentials, $scope) {
// https://developers.google.com/youtube/v3/sample_requests?hl=nl
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'useragent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
'url' => 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true',
'returntransfer' => true,
'httpheader' => array(
'Authorization: Bearer ' . $oauth2Credentials[$scope]['access_token'],
'Accept-Encoding: gzip, deflate'
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$content = $response['maps']->getContent();
$this->output = JSON::decode(gzdecode($content));
}
}
It looks like you may be running into a problem I had as well.
The call to Google_Auth_AssertionCredentials actually requires more parameters than you're sending to work with a service account. (At least, it did in my case.)
You need to pass enough parameters to include sub (which user to take actions on account of).
Without that, I always got an access denied. This clearly isn't obvious, since there's even been a function added to the php library, loadServiceAccountJson, which is supposed to set up a service account client connection, but breaks because it doesn't set sub either.
See working code here: Google php client library loadServiceAccountJson broken - fix enclosed

Read gmail with Zend Framework

Im trying to read mails from a gmail apps account by using Zend Framework. I've just transfered the Zend Framework dir to my server (path: /Zend/library/).
How do I load the Zend Framework and the Mail module? And how do I further read the mail?
I've tried the following with no results:
$path = 'Zend/library/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
I believe the syntax for reading the inbox is something like:
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com', 'user' => "name#domain.com", 'password' => "mypassword", 'ssl' => 'SSL'));
EDIT
The following code works:
$path = 'Zend/library/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com',
'user' => 'mail#domain.com',
'password' => 'password',
'ssl' => 'SSL'));
echo $mail->countMessages();`
... but when i try to echo unread emails:
echo "Unread mails:\n";
foreach ($mail as $message) {
if ($message->hasFlag(Zend_Mail_Storage::FLAG_SEEN)) {
continue;
}
// mark recent/new mails
if ($message->hasFlag(Zend_Mail_Storage::FLAG_RECENT)) {
echo '! ';
} else {
echo ' ';
}
echo $message->subject . "\n";
}
I get the following message:
Fatal error: Uncaught exception 'Zend_Mail_Storage_Exception' with message 'cannot login, user or password wrong' in /var/www/zvinx.dk/test/Zend/library/Zend/Mail/Storage/Imap.php:279 Stack trace: #0 /var/www/zvinx.dk/test/gmail.php(11): Zend_Mail_Storage_Imap->__construct(Array) #1 {main} thrown in /var/www/zvinx.dk/test/Zend/library/Zend/Mail/Storage/Imap.php on line 279
It says the username or password is wrong, which is weird cause I didnt change it from when it was working... How come this error occur?
the gmail settings are a little tricky. try:
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com',
'user' => 'mail#domain.com',
'port' => '993',
'password' => 'password',
'ssl' => 'tls',
'auth' => 'login'
));
NOTE: the gmail are using the SSL/TLS protocol which apparently is different than the standard SSL.
You really don't think that you can start using Zend Framework without reading/learning about the basics of the framework? At least take a look at the quickstart on how to use the framework with the autoloading features and then dive into the Zend_Mail documentation, more specifically the part that says "Reading Mail Messages"
There are the login setting i use to read emails via IMAP and dump attached files
public function imapAction()
{
$config = array('host'=> 'imap.gmail.com',
'user' => 'xx',
'password' => 'xx',
'ssl' => 'SSL',
'port' => 993);//995 pop, imap 993
$mail = new Zend_Mail_Storage_Imap($config);
$maxMessage = $mail->countMessages();
$this->logger->info($maxMessage);
for ($i = $maxMessage; $i <= $maxMessage; $i++)
{
$message = $mail->getMessage($i);
$this->logger->info($i.'Mail from '.$message->from.':'.$message->subject);
if($message->isMultipart())
{
$this->logger->info("has attachments");
$part = $message->getPart(2);
$cnt_typ = explode(";" , $part->contentType);
$name = explode("=",$cnt_typ[1]);
$filename = $name[1];//It is the file name of the attachement in browser
//This for avoiding " from the file name when sent from yahoomail
$filename = str_replace('"'," ",$filename);
$this->logger->info($filename);
$attachment = base64_decode($part->getContent());
$fhandle = fopen($filename, 'w');
fwrite($fhandle, $attachment);
fclose($fhandle);
}
}
}
I had the same issue and this instruction has helped me.
Quit all mail clients that are accessing the affected Gmail account. This means the Mail app on the iPhone and any other place you are accessing your Gmail from such as a computer.
Open browser and navigate to this page: http://www.google.com/accounts/DisplayUnlockCaptcha
Enter your full Gmail address, password and type the characters you see in the picture. Touch the unlock button to verify your account.
Try to read mails from a gmail apps account by using Zend Framework. Your Gmail access should be restored.
If you encounter this error and you are 100% sure about the password you provided it might come from the 2 factor authentication you set on your google account.
Google help gives indications on what to do in this case. I manage to get access to my account by generating an AppPassword in my case

Using PHP and OAuth, I'm trying to authenticate and retrieve the email address and name of a Google account

I don't really know where to go from here. I'm using the "oauth-php" library from Google Code found here: http://code.google.com/p/oauth-php/
I'm able to go as far as receiving an HTTP response with the "oauth_verifier" and "oauth_token" variables. What do I do from here? How do I access the authenticated user's email address and possibly their name? I really JUST want to know their email address like "user#example.com".
Thanks a million! Here's my code so far:
<?php
// SETTINGS
error_reporting(E_ALL);
ini_set('display_errors', 1);
// INCLUDES
include_once './php/OAuth/OAuthStore.php';
include_once './php/OAuth/OAuthRequester.php';
// CONSTANTS
define('CONSUMER_KEY', '...');
define('CONSUMER_SECRET', '...');
define('OAUTH_HOST', 'https://www.google.com');
define('REQUEST_TOKEN_URL', OAUTH_HOST . '/accounts/OAuthGetRequestToken');
define('AUTHORIZE_URL', OAUTH_HOST . '/accounts/OAuthAuthorizeToken');
define('ACCESS_TOKEN_URL', OAUTH_HOST . '/accounts/OAuthGetAccessToken');
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV['TMP']));
// Init the OAuthStore
$options = array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET,
'server_uri' => OAUTH_HOST,
'request_token_uri' => REQUEST_TOKEN_URL,
'authorize_uri' => AUTHORIZE_URL,
'access_token_uri' => ACCESS_TOKEN_URL
);
// Note: do not use "Session" storage in production. Prefer a database
// storage, such as MySQL.
OAuthStore::instance('Session', $options);
// OAUTH
try
{
// STEP 1: If we do not have an OAuth token yet, go get one
if (empty($_GET['oauth_token']))
{
$getAuthTokenParams = array(
'scope' => 'http://docs.google.com/feeds/',
'xoauth_displayname' => 'OAuth test',
'oauth_callback' => '...'
);
$tokenResult = OAuthRequester::requestRequestToken(CONSUMER_KEY, 0, $getAuthTokenParams);
// redirect to the google authorization page, they will redirect back
header('Location: ' . AUTHORIZE_URL . '?btmpl=mobile&oauth_token=' . $tokenResult['token']);
}
else
{
// STEP 2: Get an access token
$oauthToken = $_GET['oauth_token'];
$tokenResult = $_GET;
try {
OAuthRequester::requestAccessToken(CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
} catch (OAuthException2 $e) {
return;
}
}
}
catch (OAuthException2 $e)
{
echo 'OAuthException: ' . $e->getMessage();
var_dump($e);
}
Here's a sample application demonstrating how you can use the userinfo API (which provides the user's email address) with the Google API PHP Client:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/userinfo/index.php

Categories