How to access a shared folder using python imaplib? - python-3.x

How do you access a shared folder ? This is a shared folder which is visible to other users too. I am currently using outlook where the shared folder is visible along with my personal emails

Following back on my question. After reading enough this seems to work.
While using imaplib and connecting to exchange in python 3
use this,
result, data=mail.login('personal#domain.com\shared#domain.com','personalPassword')
If you have access to this shared mailbox in outlook then you will be able to connect using this. Print the result if it says 'OK' then the code did work.

I believe this is an answer.
Posting a link here for those who are working on similar problem with a python solution.
https://medium.com/#theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab
Here is the snippet:
from exchangelib import Credentials, Account
credentials = Credentials('Firstname.Lastname#someenterprise.com', 'Your_Password_Here')
account = Account('**shared_mail_box_name#someenterprise.com**', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)

Related

python MSAL patch request "The OData request is not supported" marking message as read

my application has Mail.Read.Write permission for MS graph API and the application has restrict policy on exchange online . The restriction is for a security group and the mailbox folder i am trying to access is a member of that security group. get and post methods are working fine only problem is with patch . I need to mark some emails as read after processing them.
r2 = requests.patch(request_url2,
data=json.dumps(request_body2),
headers={'Content-Type': 'application/json','Authorization': 'Bearer ' + result['access_token']})
pastebin_url2 = r2.text
print("The pastebin URL is:%s"%pastebin_url2)
the same API works fine from graph explorer has anyone tried using python msal and requests...any help appreciated
Looks like the message Id changes after moving message to a different folder
so i changed my code to first mark the message as Read in Inbox and then move to a another folder instead of the other way around. I tried with ImmutableId but it also changes after moving message to different folder.

Python3.6 Ldap3 modify_dn ( Renaming + Moving User to another OU)

I'm trying to rename AD user Test_2 to testing using python LDAP3 as well as moving user to another OU too.
NOTE: instead of domain name i am using IP and rest is same.
i am successfully able to fetching user details using the same manner (Mentioned in NOTE), but during renaming and moving user one OU to other OU, i am getting negative result; the funny thing is code doesn't showing any error it is showing only FALSE result.
import ldap3
from ldap3 import Server, Connection, ALL
server=Server(host='IP',port=389,get_info=ALL)
conn=Connection(server,user='adtest\admin',password='admin#123') conn.bind()
print (conn.modify_dn('cn=Test_2,OU=Test,OU=adtest','cn=Testing'))
Check conn.result to get the reason of the failure.

Create a google contact with python3

I would like to create a contact with the google api and python3
but gdata seemsnot to be compatible with python3.
Like :
AttributeError: 'function' object has no attribute 'func_name'
Does anyone have any sample that works on how to create contact with google api in python3 ?
thanks
First, have you installed the gdata python client with pip, or with pip3? According to Google's repository, which says,
Python 3.3+ is also now supported! However, this library has not yet been > used as thoroughly with Python 3, so we'd recommend testing before
deploying with Python 3 in production,
you can use pip3, like pip3 install google-api-python-client, to reinstall it. Once that's cleared up, see the below modified sample code-block for how to create a contact by just their Name, E-mail and Phone number with Python 3:
import atom.data
import gdata.data
import gdata.contacts.client
import gdata.contacts.data
gd_client = gdata.contacts.client.ContactsClient(source='YOUR_APPLICATION_NAME')
def create_contact(gd_client):
new_contact = gdata.contacts.data.ContactEntry()
# Set the contact's name.
new_contact.name = gdata.data.Name(
given_name=gdata.data.GivenName(text='First'),
family_name=gdata.data.FamilyName(text='Last'),
full_name=gdata.data.FullName(text='Full'))
new_contact.content = atom.data.Content(text='Notes')
# Set the contact's email addresses.
new_contact.email.append(gdata.data.Email(address='handle#gmail.com',\
primary='true', rel=gdata.data.WORK_REL, display_name='E. Bennet'))
new_contact.email.append(gdata.data.Email(address='liz#example.com',\
rel=gdata.data.HOME_REL))
# Set the contact's phone numbers.
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1212',
rel=gdata.data.WORK_REL, primary='true'))
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1213',
rel=gdata.data.HOME_REL))
# Send the contact data to the server.
contact_entry = gd_client.CreateContact(new_contact)
print ("Contact's ID: {}".format(contact_entry.id.text))
return contact_entry
For read-only access to Contacts, Google has built the new People API, which works just fine with Python3 in the google-api-python-client. However, for write access you'll need to use the older GData format.
The short answer to your question is that you won't be able to get GData to work with Python3 because the gdata-python-client is no longer maintained and never had Python3 support built in (see https://github.com/google/gdata-python-client/issues/29)
However, not all hope is lost! You can still query directly to Google's REST API. Specifically, to create a contact you need to work with the https://www.google.com/m8/feeds/contacts/{userEmail}/full route (see the Contacts API documentation for more information)
The appropriate way to work with the API directly is to submit a web request using something like Python's Requests module.
CREATE_ROUTE = 'https://www.google.com/m8/feeds/contacts/default/full'
FULL_PATH = CREATE_ROUTE + '?access_token=' + ACCESS_TOKEN
import requests
r = requests.get(FULL_PATH)
print(r.text)
Where ACCESS_TOKEN is the access token you got back from Google when you authorized your access (this can still be done using google-api-python-client)

Opening a google drive file using the google drive api while I'm NOT signed in to google drive

This has really been bugging me for some time so any help to confirm or affirm this is much appreciated! This is also the first time I actually post a question despite being developing for a long time :)
So I have a nodejs app integrating with the Google Drive API and I want users to authorize multiple Google Drive accounts and be able to view and open (and in general just interact with) all files from the accounts that they add.
I authorize my app using the highest available scope: https://www.googleapis.com/auth/drive and because I don't want users to have to sign-in again when the access_token runs out so I also include the approval_prompt: "force" and ``access_type: "offline"` when I request my access tokens.
Everything is fine - I authorize nicely, I can delete files, I can open them, I can share them, I can download them. Except for one thing:
If I e.g. authorize horse#gmail.com and then beaver#gmail.com. Then I can still delete, share, download and preview files from both accounts. But I simply cannot open documents from horse#gmail.com in google docs for editing (because beaver#gmail.com is signed in on my local machine). The best I can do is getting to a point where it shows me the document, with the right account logged in in the top right corner of the screen, but asks me to sign-in with a button. When I click the button it just refreshes and give me the same message and the same screen.
What I've tried is:
Simply redirecting the user to the file resources alternateLink from the API
Taking the alternateLink and appending my access_token to it and then redirect the user to it.
(and a ton of other random things I found various places that didn't work).
In both cases I have also tried signing out from all google accounts.
Now I checked a couple of webservices like Jollicloud and Odrive that tries something similar. However, both of them appear to force the user to login to google to access a file.
Is it really true that you can do all kinds of crazy things with the users files like deleting and downloading, but you can't open them in Google Docs own apps?
Not completely sure what kind of code I should add to show you what I've got. But here's some. This is my open action (what happens when the user clicks on a file and wants to open the file in the Google Docs/Sheet/etc.) (the orientdb stuff is because we're using the OrientDB graph database - it just fetches an account where we store the tokens). The link is the link property of the file (see below):
open: function(req,res,next){
var link = req.param("link");
var uid = req.param("uid");
orientdb.select().from('Account').where({uid: uid}).one()
.then(function(account){
var URL = link + "&access_token=" + account.tokens.access_token;
res.redirect(URL);
});
}
Here's an example file document from our database (I've replaced all compromising data with a descriptive
ODocument - Class: File id: #13:20499 v.6
name : Hummer2
service : Gdrive
kind : Google Doc
created : Nov 17, 2014
changed : Nov 17, 2014
users : [MB]
uid : mrb#flowtale.com
childID : <FILE.ID>
exportLinks : {DOCX=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=docx, Open Office doc=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=odt, Rich text=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=rtf, HTML=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=html, Plain text=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=txt, PDF=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=pdf}
usernames : [<ARRAY OF USERNAMES ASSOCIATED WITH THIS FILE>]
in_hasFile : User#11:0{out_hasFile:[size=2237],out_hasAccount:[size=4],username:null,email:h#h.com,password:<SOME ENCRYPTED PASSWORD>} v2244
out_belongsTo : Account#12:3{in_belongsTo:[size=6],type:Gdrive,uid:<SOME UID>,tokens:{access_token=<OUR ACCOUNT ACCESS TOKEN>, token_type=Bearer, refresh_token=<OUR ACCOUNT REFRESH TOKEN>, expiry_date=1416258913290},rootFolderID:<ROOT FOLDER ID>,email:<THE ACCOUNT EMAIL>,filesCached:2,usersCached:2,job:4,in_hasAccount:#11:0} v15
in_folderContains : File#13:20495{out_folderContains:[size=2],name:Testhest,service:Gdrive,kind:folder,created:Oct 12, 2014,changed:Oct 12, 2014,users:[1],link:https://docs.google.com/a/flowtale.com/folderview?id=<FOLDER.ID>&usp=drivesdk,uid:mrb#flowtale.com,childID:<FOLDER.ID>,exportLinks:{},usernames:[1],parents:[1],in_hasFile:#11:0,out_belongsTo:#12:3,in_folderContains:#13:13891} v36
link : https://docs.google.com/a/flowtale.com/document/d/<FILE.ID>/edit?usp=drivesdk
Looking forward to hear if anybody can help me or have experienced this before.
Thanks!
The API will allow you to do several actions in your drive account. I haven't been able to reproduce the behavior you mention with files that I haven't granted permissions to another account.
When you authenticate through the OAuth process, you will grant access to your account only to the application which created the OAuth request. You can not edit the content of a file without manually opening it through GDocs. Therefore, when the browser opens the AlternateUrl, it will require you to login to the account, in order to access the file.

Change a document's permissions via Google Apps Script

I'm looking for sample script that resets the default permissions on an external spreadsheet based on the email address and DocumentID passed to the script. I intent to create a script that can parse information from an email message to acquire the DocumentID and email, execute the permission change from default to anyone with a link, then email the passed address with that link.
It appears that perms are controlled by the DocList API and I'm not finding samples of GAS interacting with that API.
At Google I/O 2013, DriveApp was launched. This allows developers to build use cases like Sharing to Anyone with link
https://developers.google.com/apps-script/reference/drive/
Sample code -
var quizTemplate = DriveApp.getFileById(QUIZ_TEMPLATE_ID);
quizTemplate.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.VIEW);
or
var openFile = DriveApp.getFileById(WIDE_OPEN_ID)
openFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.COMMENT);
AFAIK DocsList Services does not have a function to change the sharing mode, between private/anyone with a link/public, only to add/remove editors and viewers. But we can still achieve this by previously setting manually the share settings of a specific folder to "anyone with a link". Then, we have just to add the file to that folder to have it shared.
A script to do that is particularly simple. e.g.
function shareWithAnyoneAndEmail(documentID,email) {
var sharedFolder = DocsList.getFolderById('id-to-your-previously-shared-folder');
var file = DocsList.getFileById(documentID);
file.addToFolder(sharedFolder);
MailApp.sendEmail(email, 'Here is your file', file.getName()+'\n'+file.getUrl());
}

Resources