OAuth2 authentication error using 'python-o365' library - oauth-2.0

I have able to successfully connect and read emails using the 'python-o365' library:
Connection.oauth2('Client_ID','Client_Secret',store_token=True)
inbox = FluentInbox()
for message in inbox.fetch_next(2):
print(message.getSubject())
However, when I try to send an email using a more basic example, I am receiving a 401 response from the server.
Connection.oauth2('Client_ID','Client_Secret',store_token=True)
att = Attachment(path=FilePath)
m = Message()
m.setRecipients(EmailTo)
m.setSubject('DBM Errors Identified - ' + FileName)
m.setBody(MessageBody)
m.attachments.append(att)
m.sendMessage()
I have also tried setting the connection object and passing it through as a parameter:
auth = Connection.oauth2('Client_ID','Client_Secret',store_token=True)
m = Message(*auth=auth*)
That however results in an error message of:
TypeError: 'Connection' object is not callable
Thanks for the help!

I was able to bypass the issue by switching to a fork of the 'python-o365' library that I used above. I feel like I am probably missing something obvious with that library but this solved the problem
Here is the simplified version of the authentication flow that I have working in case it interests anyone:
scopes = ['https://graph.microsoft.com/Mail.Read'']
account = Account(('Client_Id', 'Client_Secret'], auth_method='oauth',scopes=scopes)
account.connection.get_authroization_url() #generate the url for user to authenticate
result_url = input('Paste the result URL once you have authenticated...')
account.connection.get_session() #generate a session
m = account.new_message()
m.to.add('EmailTo')
m.body = 'MessageText'
m.send()

Related

How to get oauth AccessToken in classic asp

I want to send email by connecting google via oauth
Below is the code present for C#
MailSender objMail = new MailSender();
objMail.TLS = true;
objMail.Username = "myaccount#gmail.com";
objMail.Password = "[oauth]ya29.Il-8B-88nf.......GhoNhUXKtBS-ZEQOAZ9tTWg";
...
objMail.Send();
For whole code please navigate to
https://www.aspemail.com/net_manual_03.html#3_5
To generate access token which is appended with "[oauth]" above, we are using
MailSender objMail = new MailSender();
MailSender objMail2 = objMail.GetAccessToken("GMAIL", "4/wQGBh....LtcM", false);
string AccessToken = objMail2.Username;
string RefreshToken = objMail2.Password;
int ExpiresIn = objMail2.Timeout;
I want to implement the same functionality in classic asp, but when i am creating object of "MailSender" in classic asp, it is throwing error that:
Object doesn't support this property or method:
'objMail.GetAccessToken'
Please suggest me how can i generate access token of oauth from classic asp
That error is telling you that the object you are using doesn’t recognise the method you are trying to call. In this situation the official documentation is the best resource.
Quote from GetAccessToken()
This method was introduced in version 5.5.0.1.
The likelihood here is you are using an older version of the ASPEmail COM component.
You can use the below code to output the version information;
<%
Dim Mail
Set Mail = Server.CreateObject("Persits.MailSender")
Call Response.Write("Version: " & Mail.Version)
%>

how to get the sent emails count from my account using gmail api?

iam using gmail api, in my rails application to send emails. a user can authenticate to google and send emails(it will ask for user consent. upon user approval he can send emails from his account)
my requirement is i want to show the logined user, how many emails sent from his email id in my rails app. for that im using using the below end point. but im getting an error
require 'net/http'
require 'uri'
in controler
def sent_email_count
_
api_key = "api_key_contains_smal_case_capital_case_letters_and_special_symbols"
uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key={api_key}")
#gmail_response = Net::HTTP.get_response(uri)
end
in views :-
response <%= #gmail_response >
but getting unauthorized error.
sent email count :- #Net::HTTPUnauthorized:0x00007f6f5e3e2158
i tried like below also. but its not working.(string interpoltion changes for api key)
uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key=#{api_key}")
#gmail_response = Net::HTTP.get_response(uri)
uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key=api_key")
#gmail_response = Net::HTTP.get_response(uri)
can some one help me with this
Answer
You are missing the token in your code, that's why your requests are HTTP 401 Unauthorized, I strongly recommend you to use the Official documentation Quickstart In your case, you should use the list_user_messages method.
First of all list all the messages using the q parameter as in:sent which means read all the sent messages from my Gmail and then count your array of messages. Here's an example:
# ...
# Previous quickstart code
user_id = "email#example.com"
result = service.list_user_messages(user_id=user_id, q="in:sent")
puts "count : #{result.messages.length()}\n\n"
Reference
Ruby Google API Client
Method: users.messages.list

Microsoft Graph V1 API error: OData::ServerError 503 ConcurrentItemSave: "Conflicts occurred during saving data to store

I'm having trouble debugging the issue occurs when pushing new events to Outlook Calendar using Microsoft Graph API (v1). I have tested and it's still working, but I received this error which happened a few times today from my Ruby on Rails apps with the gems mentioned in the code snippet below. And there are duplicate events added to the calendar after these errors. I have searched this issue but still got nothing. Could anyone help me to debug this problem, please? I just don't know if this issue caused by my users' actions or just API server error. Many thanks!
OData::ServerError 503 ConcurrentItemSave: "Conflicts occurred during saving data to store (saveresult: IrresolvableConflict, properties: ). Please retry the request." from "https://graph.microsoft.com/v1.0/me/calendars/AAMkADg1YmMzNjE2LTM5Y2MtNGI2NC05NjJjLWRiY2RhZTZkNDRkMABGAAAAAADZc5aq6QclSqy_4oRMVv_EBwB4ZnW6S6xLTZDSXIsgJfprAAAAAAEGAAB4ZnW6S6xLTZDSXIsgJfprAAAGEcjmAAA=/events"
Code I use to create events via api
require 'adal'
require 'microsoft_graph'
username = ENV["OUTLOOK_USERNAME"]
password = ENV["OUTLOOK_PASSWORD"]
client_id = ENV["OUTLOOK_CLIENT_ID"]
client_secret = ENV["OUTLOOK_CLIENT_SECRET"]
tenant = ENV["OUTLOOK_TENANT"]
user_cred = ADAL::UserCredential.new(username, password)
client_cred = ADAL::ClientCredential.new(client_id, client_secret)
context = ADAL::AuthenticationContext.new(ADAL::Authority::WORLD_WIDE_AUTHORITY, tenant)
resource = "https://graph.microsoft.com/"
tokens = context.acquire_token_for_user(resource, client_cred, user_cred)
callback = Proc.new { |r|
r.headers["Authorization"] = "Bearer #{tokens.access_token}"
r.headers["Prefer"] = 'outlook.timezone="Australia/Sydney"'
r.headers['Content-type'] = 'application/json'
}
#graph = MicrosoftGraph.new(
base_url: "https://graph.microsoft.com/v1.0",
cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, "metadata_v1.0.xml"),
&callback
)
#example_data
calendar_id = "my_calendar_id"
data = my_event_object
#graph.service.post("me/calendars/#{calendar_id}/events", data.to_json)

Using Doubleclick Bid Manager API

I am writing a Python program to read line items from Doubleclick Bid Manager using its API, but facing issue while making a query to getlineitems.
To Authenticate, here is my code:
authorize_url = flow.step1_get_authorize_url()
# After entering the verification for code,
code = raw_input('Code: ').strip()
credential = flow.step2_exchange(code)
I successfully get my credential as a oauth2client.client.OAuth2Credentials object.
Then using following parameters, I make a http request.
params = dict(
api_key='xxxxxxxxxxxxxxxxxx' # client secret from the API JSON file
)
url = 'https://developers.google.com/bid-manager/v1/lineitems/downloadlineitems'
r = requests.get(url = url, params=params)
But my request returns 404; not found code. Per the API guidelines (https://developers.google.com/bid-manager/v1/lineitems/downloadlineitems), you need to make following HTTP request.
POST https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/downloadlineitems?key={YOUR_API_KEY}
Any help will be appreciated.
I don't know much about python, but since the call is a POST request, should you be using requests.get()? Is there a request.post() method?

Google+ api with dart chrome app - 403 Daily Limit

I am trying to use the google_plus_v1_api + google_oauth2_client within a chrome packaged app.
Everythin works fine when i am using only the oauth2 lib:
chrome.identity.getAuthToken(new chrome.TokenDetails(interactive:true))
.then((token){
OAuth2 auth = new SimpleOAuth2(token);
var request = new HttpRequest();
request.onLoad.listen((d){print(request.response);
request.open('GET', 'https://www.googleapis.com/plus/v1/people/me');
auth.authenticate(request).then((request) => request.send());
});
But i can't make google+ lib works:
chrome.identity.getAuthToken(new chrome.TokenDetails(interactive:true))
.then((token){
OAuth2 auth = new SimpleOAuth2(token);
Plus plus = new Plus(auth);
plus.people.get('me').then((d)=>print(d));
});
Return this exception:
GET https://www.googleapis.com/plus/v1/people/me 403 (Forbidden)
Exception: APIRequestException: 403 Daily Limit for Unauthenticated
Use Exceeded. Continued use requires signup.
Am i missing something? How am i supposed to use google+ api lib?
I just saw your answer, but wanted to point out I had the same problem and solved it by setting the makeAuthRequests property of the Plus client to true:
final plusclient.Plus plus = new plusclient.Plus(auth)
..makeAuthRequests = true;
Seems like a more straightfoward solution, since the auth object already contains the token. I would've expected makeAuthRequests to be automatically set to true when constructing a Plus client with an OAuth2 object, but apparently it's not (probably an oversight).
Sorry, i figured out that this line was missing thanks to this tutorial :
plus.oauth_token = auth.token.data;
My google_plus_v1_api query is now working.
Sorry for the inconvenience.

Resources