I am using Google's Oauth 2.0 to get the user's access_token, but I dont know how to use it with imaplib to access inbox.
Below is the code for IMAP with oauth 2.0
email = 'k#example.com'
access_token = 'vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg'
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (email, access_token)
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
imap_conn.select('INBOX')
for more details see the library code.
Currently you can use OAuth 1.0 to access Gmail over IMAP and SMTP, but OAuth 2.0 is not yet supported. Here is a link to more information: https://developers.google.com/google-apps/gmail/oauth_overview
This is something I've been kicking around. I didn't want to juggle refreshing access tokens and what not myself -- I also found there was too much boilerplate code in the Google example. I decided just to write very simple wrappers that allow for OAuth2 IMAP and SMTP that utilize Credentials and Flow objects from google-api-python-client.
Hopefully this helps somebody.
https://github.com/richieforeman/oauth2gmail
IMAP does not support accessing inbox without password -> so imaplib doesnt
Related
I've been using basic auth to log in to my outlook email with imap.
imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")
Now that Microsoft moved to oauth2 I'm getting "Login failed" messages even although the credentials are correct.
Can anyone share a code example that connects with oauth2?
I found this guide, but it only shows the steps on the account side, not the actual connection in the app.
https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:~:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports.
Thanks
This is my solution,
follow this guide to create an app with necessary permissions.
https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:%7E:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports
use the following code in your app.
imap = imaplib.IMAP4_SSL(imap_host, 993)
imap.debug = 4
access_token = get_access_token_to_authenticate_imap()
imap.authenticate("XOAUTH2", lambda x:generate_auth_string(
'useremail',
access_token['access_token']))
imap.select('inbox')
I have an old Python application that suing Imaplib to read email, download attachments from email in inbox folder, But using basic authentication like:
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
But, Microsoft is about to turn off Basic Authentication for IMAP that mean I must update to OAuth 2.0 for my application to continue working. But I've searched on internet and only find example of imaplib + OAuth2 for gmail or using win32com.client which only work on Windows (my application is running on Ubuntu).
I hope that I don't have to use other library because I have to change a lot in my code.So anyone know where to find an example about using imaplib + OAuth2.0 to access outlook mail box?
I want to utilize gdata.apps.audit.service.AuditService to create mailbox export requests (specifically via createMailboxExportRequest). Is it possible to access this api authenticating via oauth or another means? I'm trying to avoid requiring a user to provide a username and password.
Here is an example piece of code:
audit_service = gdata.apps.audit.service.AuditService(domain="test.com")
#would like to not use ClientLogin
client = audit_service.ClientLogin("adm_user#test.com", "superSecretPassword") # <------
audit_service.createMailboxExportRequest(user="target_user", begin_date=None, end_date=None, include_deleted=True, search_query=None)
audit_service.getAllMailboxExportRequestsStatus()
I'm successfully using oauth2/client_secrets for other admin/audit APIs but I can't figure out how to get the createMailboxExportRequest without ClientLogin. Any help would be appreciated.
The easiest way I've found to hack OAuth 2.0 into the older GData APIs is to build the GData service (but not authorize it), then build a credentials service like you would for the newer OAuth 2.0 discovery Google APIs, then add the proper credentials as a header on the GData service:
audit_service = gdata.apps.audit.service.AuditService(domain="test.com")
... # build your credentials like normal with oauth2client
auth_headers = {u'Authorization': u'Bearer %s' % credentials.access_token}
audit_service.additional_headers = auth_headers
I'm trying to connect to the google doubeclick api through a service account (client email and p12 certificate), using the python client library as in the following example:
http://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py
It's returning me an empty access_token:
In [9]: type(credentials.access_token)
Out[9]: <type 'NoneType'>
What is the significance of this? Is there something I am likely doing wrong? I have also tried accessing the tasks api as in the example (thinking that possibly the doubleclick api is not a supported scope) but same result.
UPDATE (example code):
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from adspygoogle.dfp import DfpClient
f = file('/path/to/.ssh/google-api.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials('<email>', key, scope='https://www.google.com/apis/ads/publisher')
credentials.refresh(http)
http = httplib2.Http()
http = credentials.authorize(http)
client = DfpClient.DfpClient(headers={'networkCode': '<code>', 'applicationName': 'test', 'userAgent': 'test', 'oauth2credentials': credentials})
inventory_service = client.GetInventoryService()
inventory_service.getAdUnitsByStatement({'query':''})
ERROR:
DfpAuthenticationError: [AuthenticationError.NO_NETWORKS_TO_ACCESS # ]
The NO_NETWORKS_TO_ACCESS error specifically means that you did authenticate to the API endpoint but that your account isn't associated with a network. Search for that error on this page https://developers.google.com/doubleclick-publishers/docs/reference/v201203/InventoryService?hl=en.
You either need to have the Google account you are authenticating as invited to the network via the DoubleClick User Interface or you need to use impersonation.
A more specific writeup on DFP API and service accounts was recently posted https://developers.google.com/doubleclick-publishers/docs/service_accounts to the documentation. I suggest you look at the alternative section of that documentation to determine if you might prefer an OAuth 2.0 installed flow.
I'm trying to use the Google Docs API with Python+Django and OAuth 2. I've got the OAuth access token, etc. via google-api-python-client, with the code essentially copied from http://code.google.com/p/google-api-python-client/source/browse/samples/django_sample/plus/views.py
Now, I assume I should be using the google gdata API, v 2.0.17. If so, I'm unable to find exactly how to authorize queries made using the gdata client. The docs at http://packages.python.org/gdata/docs/auth.html#upgrading-to-an-access-token (which appear outdated anyway), say to set the auth_token attribute on the client to an instance of gdata.oauth.OAuthToken. If that's the case, what parameters should I pass to OAuthToken?
In short, I'm looking for a brief example on how to authorize queries made using the gdata API, given an OAuth access token.
The OAuth 2.0 sequence is something like the following (given suitably defined application constants for your registered app).
Generate the request token.
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT)
Authorise the request token. For a simple command-line app, you can do something like:
print 'Visit the following URL in your browser to authorise this app:'
print str(token.generate_authorize_url(redirect_url=REDIRECT_URI))
print 'After agreeing to authorise the app, copy the verification code from the browser.'
access_code = raw_input('Please enter the verification code: ')
Get the access token.
token.get_access_token(access_code)
Create a gdata client.
client = gdata.docs.client.DocsClient(source=APP_NAME)
Authorize the client.
client = token.authorize(client)
You can save the access token for later use (and so avoid having to do the manual auth step until the token expires again) by doing:
f = open(tokenfile, 'w')
blob = gdata.gauth.token_to_blob(token)
f.write(blob)
f.close()
The next time you start, you can reuse the saved token by doing:
f = open(tokenfile, 'r')
blob = f.read()
f.close()
if blob:
token = gdata.gauth.token_from_blob(blob)
Then, the only change to the authentication sequence is that you pass this token to OAuth2Token by specifying a refresh_token argument:
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT,
refresh_token=token.refresh_token)
Hope this helps. It took a while to work it out :-).
This is from https://developers.google.com/gdata/docs/auth/overview:
Warning: Most newer Google APIs are not Google Data APIs. The Google Data APIs documentation applies only to the older APIs that are listed in the Google Data APIs directory. For information about a specific new API, see that API's documentation. For information about authorizing requests with a newer API, see Google Accounts Authentication and Authorization.
You should either use OAuth for both authorization and access or OAuth 2.0 for both.
For OAuth 2.0 API are now at https://developers.google.com/gdata/docs/directory.