modifying microsoft outlook contacts from python

  • Last Update :
  • Techknowledgy :

The code is straightforward.

import win32com.client
import pywintypes

o = win32com.client.Dispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
profile = ns.Folders.Item("My Profile Name")
contacts = profile.Folders.Item("Contacts")
contact = contacts.Items[43] # Grab a random contact,
   for this example.
print "About to overwrite ", contact.FirstName, contact.LastName
contact.categories = 'Supplier'
# Override the categories

# Edit: I don 't always do these last steps.
ns = None
o = None

Suggestion : 2

If you find copyright violations, you can contact us at info@generacodice.com to request the removal of the content.,I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record.,I open the contact and its category HAS changed, sometimes. (Not sure of when, but it feels like it is cache related.) If it has changed, it prompts me to Save Changes when I close it which is odd, because I haven't changed anything in the Outlook UI.,At this point, I change over to Outlook, which is opened to the Detailed Address Cards view.

The code is straightforward.

import win32com.client
import pywintypes

o = win32com.client.Dispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
profile = ns.Folders.Item("My Profile Name")
contacts = profile.Folders.Item("Contacts")
contact = contacts.Items[43] # Grab a random contact,
   for this example.
print "About to overwrite ", contact.FirstName, contact.LastName
contact.categories = 'Supplier'
# Override the categories

# Edit: I don 't always do these last steps.
ns = None
o = None

Suggestion : 3

06/18/2022

private void AddContact() {
   Outlook.ContactItem newContact = (Outlook.ContactItem)
   this.Application.CreateItem(Outlook.OlItemType.olContactItem);
   try {
      newContact.FirstName = "Jo";
      newContact.LastName = "Berry";
      newContact.Email1Address = "somebody@example.com";
      newContact.CustomerID = "123456";
      newContact.PrimaryTelephoneNumber = "(425)555-0111";
      newContact.MailingAddressStreet = "123 Main St.";
      newContact.MailingAddressCity = "Redmond";
      newContact.MailingAddressState = "WA";
      newContact.Save();
      newContact.Display(true);
   } catch {
      MessageBox.Show("The new contact was not saved.");
   }
}
Private Sub AddContact()
Dim newContact As Outlook.ContactItem = Me.Application.CreateItem(Outlook._ OlItemType.olContactItem)
Try
With newContact
   .FirstName = "Jo"
   .LastName = "Berry"
   .Email1Address = "somebody@example.com"
   .CustomerID = "123456"
   .PrimaryTelephoneNumber = "(425)555-0111"
   .MailingAddressStreet = "123 Main St."
   .MailingAddressCity = "Redmond"
   .MailingAddressState = "WA"
   .Save()
   .Display(True)
End With
Catch
MsgBox("The new contact was not saved.")
End Try
End Sub

Suggestion : 4

This guide explains how to use the Nylas Python SDK and Contacts API to create Google and Microsoft (Exchange, Outlook, Office365) contacts and modify their attributes. It covers the following steps:,Learn how to manage Google and Microsoft contacts with the Nylas Python SDK. Build your contacts book integration in 15 minutes.,If you’ve made it this far, congrats, you’ve successfully learned how to manage Google and Microsoft contacts with the Nylas Contacts API! There is plenty more that you can do with it: take a look at the following resources to learn more about the Nylas Communications Platform capabilities.,Once the contact has been saved and synced to Google, you should see a contact that looks something like this:

With your virtual environment activated, run:

pip install nylas

At its core, the Nylas Communication Platform is an API client that interfaces with all of the major contact book providers. First, import the APIClient class from the nylas package, and create a new instance of this class, passing the variables you gathered when you got your developer API keys. In the following example, replace CLIENT_ID, CLIENT_SECRET, and ACCESS_TOKEN with your values.

from nylas
import APIClientnylas = APIClient(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN)

The next example demonstrates how to display the first and last name, email address, and ID for the first 10 contacts returned from an account. The first step is to get a list of contact objects. The following example uses the nylas object to return the first 10 contacts from the user account.

contacts = nylas.contacts.all(limit = 10)

Here is the entire code example to list contacts for a user account.

from nylas
import APIClientnylas = APIClient(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN, ) contacts = nylas.contacts.all(limit = 10) for contact in contacts: # contact.emails returns a defaultdict() object # that contains a list of email addresses with their appropriate labels email = list(contact.emails.values())[0][0] print("Name: {} {} | Email: {} | ID: {}".format(contact.given_name, contact.surname, email, contact.id))

To create a contact, use nylas to create a new contact object:

contact = nylas.contacts.create()

Suggestion : 5

Good Abstraction layer between each Api. Change the api (Graph vs Office365) and don't worry about the api internal implementation.,Microsoft Graph and Office 365 API made easy,This project aims to make interacting with Microsoft Graph and Office 365 easy to do in a Pythonic way. Access to Email, Calendar, Contacts, OneDrive, etc. Are easy to do in a way that feel easy and straight forward to beginners and feels just right to seasoned python programmer.,This section is explained using Microsoft Graph Protocol, almost the same applies to the Office 365 REST API.

For Example (following the previous permissions added):

from O365
import Account
credentials = ('my_client_id', 'my_client_secret')

# the
default protocol will be Microsoft Graph
# the
default authentication method will be "on behalf of a user"

account = Account(credentials)
if account.authenticate(scopes = ['basic', 'message_all']):
   print('Authenticated!')

# 'basic'
adds: 'offline_access'
and 'https://graph.microsoft.com/User.Read'
# 'message_all'
adds: 'https://graph.microsoft.com/Mail.ReadWrite'
and 'https://graph.microsoft.com/Mail.Send'

For Example:

from O365
import Account

credentials = ('my_client_id', 'my_client_secret')

# the
default protocol will be Microsoft Graph

account = Account(credentials, auth_flow_type = 'credentials', tenant_id = 'my-tenant-id')
if account.authenticate():
   print('Authenticated!')

You can authenticate using a console. The best way to achieve this is by using the authenticate method of the Account class.

account = Account(credentials)
account.authenticate(scopes = ['basic', 'message_all'])

The following example is done using Flask.

@route('/stepone')
def auth_step_one():

   callback = 'my absolute url to auth_step_two_callback'
account = Account(credentials)
url, state = account.con.get_authorization_url(requested_scopes = my_scopes,
   redirect_uri = callback)

# the state must be saved somewhere as it will be needed later
my_db.store_state(state) # example...

   return redirect(url)

@route('/steptwo')
def auth_step_two_callback():
   account = Account(credentials)

# retreive the state saved in auth_step_one
my_saved_state = my_db.get_state() # example...

   # rebuild the redirect_uri used in auth_step_one
callback = 'my absolute url to auth_step_two_callback'

result = account.con.request_token(request.url,
   state = my_saved_state,
   redirect_uri = callback)
#
if result is True, then authentication was succesful
# and the auth token is stored in the token backend
if result:
   return render_template('auth_complete.html')
#
else....

Save message as "eml":

    msg.save_as_eml(to_path = Path('my_saved_email.eml'))

Carefull: there's no way to identify that an attachment is in fact a message. You can only check if the attachment.attachment_type == 'item'. if is of type "item" then it can be a message (or an event, etc...). You will have to determine this yourself.

    msg_attachment = msg.attachments[0] # the first attachment is attachment.attachment_type == 'item'
    and I know it 's a message.
    msg.attachments.save_as_eml(msg_attachment, to_path = Path('my_saved_email.eml'))