I'm using pywin32 to write a program that sends email notifications. Based on error exceptions
def main(recipient):
try:
mailer = Dispatch("Outlook.Application")
msg = mailer.CreateItem(0)
msg.To = recipient
msg.CC = ""
msg.Subject = "EmailTest"
msg.Body = "This is most certainly a test"
msg.Send()
success(msg.Subject, recipient)
except Exception:
failure(msg.Subject, recipient)
When the parameters to the success and fail methods are variables (with string values) it returns the error:
Traceback (most recent call last):
File "C:\pathtoprogram\thisprogram.py", line 48, in main
success(msg.Subject, recipient)
File "C:\Users\myuser\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The item has been moved or deleted.', None, 0, -2147221238), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\pathtoprogram\thisprogram.py", line 50, in main
failure(msg.Subject, recipient)
File "C:\Users\myuser\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The item has been moved or deleted.', None, 0, -2147221238), None)
I don't know what's creating the exception, but the code works fine when I enter the parameters directly as strings.
success("mySubject", "anEmail")
except Exception:
failure("mySubject", "anEmail")
That code works will run fine, but I need the parameters to be variables because they need to be able to be passed in from the main method.
I've been looking up answers to similar problems but I haven't found one that pertains to this issue. It seems like msg.Subject and msg.To don't actually store string values even though they're in what looks like any other assignment statement. Maybe it's an obvious thing I'm missing?
Any help would be greatly appreciated.
I'm using python 3.6 and the corresponding version of pywin32.
The problem is not with the way you are using the variables. You can test this by checking the values of msg.Subject before you call msg.Send()
Refer to the CDO (collaboration data objects) documentation from Microsoft, specifically for the Send method:
https://msdn.microsoft.com/en-us/library/ms527190(v=exchg.10).aspx
Send moves the message to the current users Outbox folder. Messaging systems retrieve messages from the Outbox and transport them to the recipients. After it is transported, a message is removed from the Outbox and deleted unless saveCopy is True.*
Refer to the error message you were getting:
4096, 'Microsoft Outlook', 'The item has been moved or deleted.'
So the system is doing what it was designed to do - delete the message after you send it.
Related
I have a .NET 6.0 COM library that I am trying to use with Python 3.9. I additionally wrote an idl file to create a tlb and registered the COM object using regsvr32. The registration seems fine as the registry entries look good and I can also use the object with other COM clients such as Excel and LabWindows. However, when using the COM object in a python script I get the following errors:
Traceback (most recent call last):
File "path\Python39\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
line 5, in Init
test = win32com.client.Dispatch("ComTest")
File "path\Python39\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "path\Python39\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "path\Python39\site-packages\win32com\client\dynamic.py", line 83, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147467262, 'No such interface supported', None, None)
My code looks like this:
Python:
import win32com.client
def Init():
test = win32com.client.Dispatch("ComTest")
test.SomeMethod(1, 2, "test")
if __name__ == "__main__":
Init()
C#:
Interface
[ComVisible(true)]
[Guid(AssemblyInfo.InterfaceGuid)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComTest
{
public double SomeMethod(double param1, double param2, string param3);
}
Class
[ComVisible(true)]
[Guid(AssemblyInfo.ClassGuid)]
[ProgId("ComTest")]
public class ComTest : IComTest
{
public double SomeMethod(double param1, double param2, string param3)
{
// implementation
}
}
I first thought it might be some issue with different bit versions but that does not seem to be the problem either. I tried installing a 32 bit version of python and testing it with that but I still got the same error. Does someone know what might cause the problem? Thanks for your help.
I'm trying to use pywin32 to manipulate SAS Enterprise Guide using Python. But I'm running into some errors. I've tried both Dispatch and EnsureDispatch, but both return the same error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 89, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\xxxxxxx\Desktop\test.py", line 4, in <module>
sas = EnsureDispatch('SASEGObjectModel.Application.7.1')
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\gencache.py", line 527, in EnsureDispatch
disp = win32com.client.Dispatch(prog_id)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)
(This is using EnsureDispatch, the error using Dispatch is almost the same, only without the 2nd and 3rd lines after the second traceback).
Also, I've tried running makepy (from the same lib) to see what it would return, and I get the following message:
Could not locate a type library matching 'SASEGObjectModel.Application.7.1'
If I try doing it using vbs, using the following code:
Set app = CreateObject("SASEGObjectModel.Application.7.1")
WScript.echo app.Name
It shows a message box with 'Enterprise Guide' written, showing that the object is available to the system.
I've tried asking for help over SAS Support Community, and after many interesting suggestions, I still couldn't solve the issue. But one thing that I hadn't tried, and ended up working, was install a fresh python installation (Not Anaconda), installing PyWIN and it simply worked.
I am trying to remove a user from a security group using Python and pywin32, but so far have not been successful. However I am able to add a user to a security group.
from win32com.client import GetObject
grp = GetObject("LDAP://CN=groupname,OU=groups,DC=blah,DC=local")
grp.Add("LDAP://CN=username,OU=users,DC=blah,DC=local") # successfully adds a user to the group
grp.Remove("LDAP://CN=username,OU=users,DC=blah,DC=local") # returns an error
The error is below:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in Remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
I have also tried adding using GetObject to get the user and remove it that way, however I get the same error.
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
Any help would be much appreciated as I've hit a dead-end here.
EDIT
I have also now tried using Tim Golden's active_directory module to try and remove the group member.
import active_directory as ad
grp = ad.find_group("groupname")
usr = ad.find_user("username")
grp.remove(usr.path())
However this also doesn't work, and I encounter the below error.
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 802, in __getat
tr__
attr = self.com_object.Get(name)
pywintypes.com_error: (-2147463155, 'OLE error 0x8000500d', (0, 'Active Director
y', 'The directory property cannot be found in the cache.\r\n', None, 0, -214746
3155), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\site-packages\active_directory.py", line 1081, in remove
self.group.Remove(dn)
File "C:\Python33\lib\site-packages\active_directory.py", line 804, in __getat
tr__
raise AttributeError
AttributeError
EDIT
Wherby suggested that I change to Python 2.7 and give that a go. I have just tried this:
import active_directory as ad
user = ad.find_user("username")
group = ad.find_group("groupname")
group.remove(user.path())
... but I'm still getting an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
The user and group are definitely found correctly, as I can print their LDAP paths using print user.path() and print group.path()
Are there any other active directory libraries for Python 3.3 that anyone can recommend?
From
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
The error indicate you are using not existed "group name", the function find_group required anexisted group name, but you give not existed name.
You should double check "Tim Golden's active_directory module" 's manual.
For
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
I suggest you add "print user" to see if the user really get.
Well, I've gone and figured out I was being a bit of a muppet. The account I was logged in to didn't have the permissions to delete from AD groups. When I logged in as the network admin account it worked like a charm.
The final code:
from win32com.client import GetObject
group = GetObject("LDAP://CN=groupname,OU=Groups,DC=blah,DC=local")
group.Remove("LDAP://CN=username,OU=Users,DC=blah,DC=local")
Environment: Windows 2008 R2 x64, IIS 7
I'm trying to add "Application" and "Application Pool" to IIS. IIS is configured and is running just fine. I've manually added sites/applications - and they work fine as well.
import wmi
oWebAdmin = wmi.GetObject(r"winmgmts:root\WebAdministration")
strApplicationPath = "/my_site"
strSiteName = "Default Web Site"
strPhysicalPath = r"C:\Windows\SysNative\certsrv\mscep"
#fails here:
oWebAdmin.Get('Application').Create(strApplicationPath, strSiteName, strPhysicalPath)
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
I get the error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 23, in <module>
oWebAdmin.Get('Application').Create(strApplicationPath, strSiteName, strPhysicalPath)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
The interesting part is that .Create() from msdn says all the parameters I put are valid.
What have I tried:
1) to create Application Pool first (however the order should not matter, since I need to bind them when they are both created)
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
and, of course, I get the very similar error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 17, in <module>
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
2) I've tried to list the applications. And that works:
oApps = oWebAdmin.InstancesOf("Application")
for app in oApps:
print app.SiteName
print app.Path
print app.ApplicationPool
print app.EnabledProtocols
Output:
Default Web Site
/
DefaultAppPool
http
Default Web Site
/CertSrv/mscep_admin
SCEP
http
Default Web Site
/CertSrv/mscep
SCEP
http
MyApp
/
MyApp AppPool
http
What could be wrong with my .Create() call?
NOTE: I'm running with elevated privileges (if that matters)
UPDATE: Could .Get be failing?: No, it's definetely .Create():
app = oWebAdmin.Get('Application')
#fails here:
app.Create(strApplicationPath, strSiteName, strPhysicalPath)
error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 18, in <module>
app.Create(strApplicationPath, strSiteName, strPhysicalPath)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
Are you sure it's not the GET that's failing?
I am trying to open an excel file in python using COM, and trying to catch the file not found error:
I first tried catching the IOError:
try:
output = xl.Workbooks.Open(Params.workbookName)
except IOError as reason:
print reason
exit()
But COM doesn't raise an IO Error when it has a file not found problem, instead it raises something called com_error:
com_error: (-2147352567, 'Exception
occurred.', (0, u'Microsoft Office
Excel', u"'asdf.xlsx' could not be
found. Check the spelling of the file
name, and verify that the file
location is correct.\n\nIf you are
trying to open the file from your list
of most recently used files, make sure
that the file has not been renamed,
moved, or deleted.", u'C:\Program
Files (x86)\Microsoft
Office\Office12\1033\XLMAIN11.CHM',
0, -2146827284), None)
so logically I tried this:
try:
output = xl.Workbooks.Open(Params.workbookName)
except com_error as reason:
print reason
exit()
but...
NameError: global name 'ComError' is not defined
Try:
from pythoncom import com_error
and catch it in your except block