python-3.xpywin32win32comwin32gui

Sending emails from outlook with Python not working


I have been running some code for a while which automates some emails using win32com.client. All has been working for months but today I am getting an error.

import win32com.client

olMailItem = 0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)

Today I get the error AttributeError: module 'win32com.gen_py.00062FFF-0000-0000-C000-000000000046x0x9x6' has no attribute 'CLSIDToPackageMap'

If I try "Excel.Application" or "Word.Application" then I don't get an error and Outlook is installed and working on my system. Last week I came across the issue where mail.Bcc and mail.HTMLbody changed to mail.BCC and mail.HTMLBody respectively but I've not found that a change in the string has helped.

Can anyone shed any light on what might be happening?

Thanks in advance.


Solution

  • You might have to remove some old files:

    # If errors are found, do this
    # clear contents of C:\Users\<username>\AppData\Local\Temp\gen_py
    # that should fix it, to test it type
    import win32com.client
    app = win32com.client.gencache.EnsureDispatch("Outlook.Application")
    app.Visible = True
    

    This gist also has other solutions that remove the files automatically. Application needs to be adjusted.

    1.)

    from pathlib import Path
     try:
            xl = win32.gencache.EnsureDispatch('Excel.Application')
        except AttributeError:
            f_loc = r'C:\Users\<username>\AppData\Local\Temp\gen_py'
            for f in Path(f_loc):
                Path.unlink(f)
            Path.rmdir(f_loc)
            xl = win32.gencache.EnsureDispatch('Excel.Application')
    

    2.)

    try:
        xl = client.gencache.EnsureDispatch('Excel.Application')
    except AttributeError:
        # Corner case dependencies.
        import os
        import re
        import sys
        import shutil
        # Remove cache and try again.
        MODULE_LIST = [m.__name__ for m in sys.modules.values()]
        for module in MODULE_LIST:
            if re.match(r'win32com\.gen_py\..+', module):
                del sys.modules[module]
        shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
        from win32com import client
        xl = client.gencache.EnsureDispatch('Excel.Application')