MAPI not Defined - python

I had a code that ran well for 3 months up until now I have started seeing errors and not sure what needs revision
My original code was this:
import pandas as pd
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
root_folder = namespace.Folders.Item(3)
subfolder = root_folder.Folders['Inbox'].Folders['Daily Process']
messages = subfolder.Items
message = messages.GetFirst()
subj_line = message.subject
However I am getting the following error
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed. An object could not be found.', None, 0, -2147221233), None)
I broke my code down and seems like the name 'MAPI' is not longer defined
import pandas as pd
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
your_folder = namespace.Folders['Inbox'].Folders['Daily Process']
for message in your_folder.Items:
print(message.Subject)
Which gives me
name 'mapi' is not defined

Try in lower case:
outlook = win32com.client.Dispatch("outlook.application")
I also had the same error when I put capitalized Outlook

Related

com_error when saving emails in windows outlook with python

I'm using python to save emails in a specified folder and complete the following:
check if the email is unread
save the email to target folder
mark the message as read
tell me how many messages were archived and the location
the code:
from win32com.client import Dispatch
import os
outlook = Dispatch('outlook.application').GetNamespace("MAPI")
root = outlook.Folders[0].Folders[27]
targetPath = os.path.expanduser(r'\\path\to\target\folder')
messages = root.Items
count = 0
for msg in messages:
if msg.UnRead:
msg.SaveAs(os.path.join(targetPath))
msg.UnRead = False
count +=1
print(str(count)+' emails archived to: '+targetPath)
I end up with this error i've never seen before, and I haven't had any luck with the google machine... so I come to stackoverflow and wake you from your slumber.
Traceback (most recent call last):
File "C:\Users\e582324\Documents\Python Scripts\untitled6.py", line 18, in <module>
msg.SaveAs(os.path.join(targetPath))
File "<COMObject <unknown>>", line 3, in SaveAs
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The operation failed.', None, 0, -2147024829), None)
Any idea whats causing this? I have a similar script that saves just attachments and it works fine. My target folder is on a network shared drive for both scripts and it hasn't caused an issue until now. Only real difference is the use of .SaveAs() instead of .SaveAsFile()
You need to specify the file name as well as its extension. passing the path is not enough sometimes, especially when you don't specify the format (see the second parameter). Note, an Outlook folder may contain different kind of items - mail items, appointments, documents, notes and etc. For example, here is a sample:
Item.SaveAs Environ("HOMEPATH") & "\My Documents\" & strname & ".txt", olTXT
Also I've noticed that you are iterating over all items in the folder:
for msg in messages:
if msg.UnRead:
Instead, you need to use the Find/FindNext or Restrict methods of the Items class. So, you get only items that correspond to your conditions and iterate only over them. Read more about these methods in the following articles:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder

Python: ValueError: microsecond must be in 0..999999 while using win32com

I'm currently trying calculate the leadtime of all outlook messages within a specific outlook folder using python. In general the script runs fine however, after roundabout 2000 emails I received the following error (part of code):
import win32com.client as win32
import pandas as pd
from datetime import date
import time
outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("example#example.com")
inbox = folder.Folders("Inbox")
messages = inbox.Items
df = pd.DataFrame()
index = 0
for msg in messages:
if (msg.SenderEmailType != "EX"):
print(str(msg.subject))
print('Begin date:', msg.SentOn.strftime('%Y-%m-%d'))
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
df.at[index, 'Subject'] = msg.subject
df.at[index, 'Begin date'] = msg.SentOn.strftime('%Y-%m-%d')
df.at[index, 'End date'] = msg.LastModificationTime.strftime('%Y-%m-%d')
I encounterd the following error:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\MailCounts.py", line 24, in <module>
print('End date:',msg.LastModificationTime.strftime('%Y-%m-%d'))
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
I tried to debug it by selecting the specific email and put it into another outlook folder and then loop over it. But then it works fine without errors. So it seems to be folder specific?!
I have searched for several answers on the errors and the method in general. But as far as I can see, this answer was never asked before with a suitable answer.
Thanks in advance!

TypeError: '_Folders' object is not callable

I'm using win32.client and trying to manipulate email body text.
This was working today but I think when testing I might have broken Outlook! When I try to call an index of a _Folders object, I get a type error that it is uncallable.
I use indexes to get into my nested folders. This was working until tonight and I haven't changed any of the code.
import win32com.client
import urllib.parse
import webbrowser
from pyshorteners import Shortener
application = win32com.client.Dispatch('Outlook.Application')
namespace = application.GetNamespace('MAPI')
# 6 is the number for the main inbox
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox(3)
mobile_folder_directory = mobile_folder.Folders
mobile_script_folder = mobile_folder_directory(2)
# using Items method to parse specific email files within the folder
messages = inbox_folder.Items
I get this error:
File "mail1.py", line 10, in mobile_folder = inbox_folders(3) TypeError: '_Folders' object is not callable
I was messing around with other code trying to monitor my inbox for new mail.
I ran some of this code in another file with some modifications to match my inboxes
import ctypes # for the VM_QUIT to stop PumpMessage()
import pythoncom
import win32com.client
import sys
# outlook config
SHARED_MAILBOX = "Your Mailbox Name"
# get the outlook instance and inbox folder
session = win32com.client.Dispatch("Outlook.Application").Session
user = session.CreateRecipient(SHARED_MAILBOX)
shared_inbox = session.GetSharedDefaultFolder(user, 6).Items # 6 is Inbox
class HandlerClass(object):
def OnItemAdd(self, item):
print("New item added in shared mailbox")
if item.Class == 43:
print("The item is an email!")
outlook = win32com.client.DispatchWithEvents(shared_inbox, HandlerClass)
def main():
print("Starting up Outlook watcher")
pythoncom.PumpMessages()
if __name__ == "__main__":
try:
status = main()
sys.exit(status)
except KeyboardInterrupt:
print("Terminating program..")
ctypes.windll.user32.PostQuitMessage(0)
sys.exit()
My suspicion is that it changed something with Outlook versions.
I also got something saying that a MAPIFolder object isn't callable. My research was showing this is an old, unsupported Outlook protocol.
Here's more data when I try to index my folders:
>>> inbox_folder
<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x12191504>
>>> inbox = inbox_folder.Folders
>>> inbox
<win32com.gen_py.Microsoft Outlook 16.0 Object Library._Folders instance at 0x46668848>
>>> inbox(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_Folders' object is not callable
I still don't know what broke it, but it turns out that searching folders by index wasn't working anymore.
The solution was now searching by folder name:
inbox_folder = namespace.GetDefaultFolder(6)
# had to create multiple objects of subfolders to get to specific directory
inbox = inbox_folder.Folders
mobile_folder = inbox["Mobile"]
mobile_script_folder = mobile_folder.Folders["Mobile_4_4_Alpha"]
not sure why it fixed it but it did. yay!
don't know why but delete this file work in my case.
C:\Users\[user name]\AppData\Local\Temp\gen_py\[python version]\00062FFF-0000-0000-C000-000000000046x0x9x6.py
credit: https://blog.csdn.net/ericatardicaca/article/details/90721909

How get list of Databases using Dispatch('ADODB.Connection')?

I am using PIOLEDBENT provider, i need to extract list of databases in my PIAF Server when i call oConn.GetSchema i throws exception mention bellow. please guide me what is wrong with my code.
from win32com.client import Dispatch
oConn = Dispatch('ADODB.Connection')
oRS = Dispatch('ADODB.RecordSet')
oConn.ConnectionString = "Provider=PIOLEDBENT; Data Source=localhost; Integrated Security=True; Integrated Security=True;User ID=abubakr;Password=#Spark123!"
oConn.Open()
oConn.GetSchema();
Exception :
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'ADODB.Connection', u'Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.', u'C:\\Windows\\HELP\\ADO270.CHM', 1240641, -2146825287), None)

Using MAPI to retrieve the list of emails from GAL

This is my code so far:
import win32com.client
o = win32com.client.gencache.EnsureDispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
adrLi = ns.AddressLists.Item("Global Address List")
contacts = adrLi.AddressEntries
numEntries = adrLi.AddressEntries.Count
nameAliasDict = {}
for i in contacts:
name = i.Name
alias = i.Address.split("=")[-1]
print i.GetExchangeUser().PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3A56101E")
I"m getting the property from: https://msdn.microsoft.com/en-us/library/bb446002.aspx
But for some reasons, I get this error:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, u'Microsoft Outlook', u'The property "http://schemas.microsoft.com/mapi/proptag/0x3A550003" is unknown or cannot be found.', None, 0, -2147221233), None)
Am I doing this wrong?
You cannot assume that PR_CONTACT_EMAIL_ADDRESSES or any other MAPI property will be available. Your code must expect and handle that error from PropertyAccessor.GetProperty.
Check if you can actually see the property on that particular object in OutlookSpy (I am its author - click IAddrBook, "Open Root Container" etc.).
Why exactly do you need that property? If you just need the SMTP address. use ExchangeUser.PrimarySmtpAddress.

Categories