I'm relatively new to coding in general, and I'm trying to automate the process of sending a specific email I do regularly at work using Python. I found some code that seemed to accomplish my goal, but I can't get it to import the win32api module correctly.
I'm using the PyCharm IDE, and I have installed win32 using pip successfully. When I check under site-packages\win32 I can clearly see the win32api.pyd file there, together with a bunch of other files. But when I try to import it, it's not found. When I write:
from win32 import
the only option I get is _win32sysloader
The site-packages folder is in my PYTHONPATH, I have been able to import the openpyxl module in the same way, but this one is not as cooperative.
Here's the code I'm using:
import win32com.client
import win32
outlook = win32com.client.Dispatch(r"path\to\outlook.exe")
mail = outlook.CreateItem(0)
mail.To = "my@mail.com
mail.Subject = "Test"
mail.Body = "Mail"
mail.Send
In the end, what I'm trying to accomplish is to automatically send an email to a specific address with a certain text string. But when I run this code I get the error: ModuleNotFoundError: No module named 'win32api' If you have any other recommendations regarding how to accomplish this I'd be happy to hear them.
Thanks.
Win32 module is not required.
And you didn't use win32com.client.Dispatch
correctly.
Automation objects are COM objects that expose methods and properties using the IDispatch interface. So how do we use these objects from Python? The win32com.client package contains a number of modules to provide access to automation objects.
To use an IDispatch-based COM object, use the method win32com.client.Dispatch(). This method takes as its first parameter the ProgID or CLSID of the object you wish to create. If you read the documentation for Microsoft Outlook, you'll find the ProgID for Outlook is outlook.application, so to create an object that interfaces to Outlook.
You should modify it like this.
After testing, it is effective.
import win32com.client
outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = "my@mail.com"
mail.Subject = "Test"
mail.Body = "Mail"
mail.Send()
And this will use your local outlook account.