2

I am using the below code to send email with an attachment using python. I using the outlook application itselt(not via backend)

from time import sleep

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = "EMAIL ADDRESS"
mail.Subject = "Subject"
mail.HtmlBody = "HTML Body"
mail.Attachments.Add("folderName\\output.zip")
mail.Display(True)
sleep(1)
mail.Send()

Its working fine till the line mail.Display(True). I can see the outlook new mail window open with everything typed in and also file attached. But the next statement mail.send() is giving error :

Traceback (most recent call last):   File "C:/Users/username/PycharmProjects/001.PySelenium/win32email.py", line 16, in <module>
    mail.send()   File "C:\Users\username\PycharmProjects\001.PySelenium\venv\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2147467260, 'Operation aborted', None, None)

Debug Screenshot :

enter image description here

anandhu
  • 686
  • 2
  • 13
  • 40

1 Answers1

0

Please use mail.Send()

By the way, if you want send mail through outlook using Python automatically.

Please comment mail.Display(True) and sleep(1), or you cannot send a mail until you manually save changes to the mail.

Please try:

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.Attachments.Add("folderName\\output.zip")

mail.Send()
Strive Sun
  • 5,988
  • 1
  • 9
  • 26
  • Tried. But didnt work. Commented out mail.Display and sleep and changed to mail.Send(). Still its not sending the mail. Getting same error – anandhu Jan 15 '20 at 08:50
  • @automaticSoldier it's strange, I have edited my answer, please try another way. – Strive Sun Jan 15 '20 at 08:53
  • Tried, but its giving type mismatch error in line mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, send_account)) – anandhu Jan 15 '20 at 08:59
  • @automaticSoldier What is your operating environment, WIN10?Python 3? – Strive Sun Jan 15 '20 at 09:03
  • Windows 10, Python Interpreter 3.6 – anandhu Jan 15 '20 at 09:05
  • @automaticSoldier My test is successful. I used 3.7, and my outlook version is 2016. – Strive Sun Jan 15 '20 at 10:02
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/205994/discussion-between-strive-sun-msft-and-automaticsoldier). – Strive Sun Jan 15 '20 at 10:02
  • I have related type mismatch error - Can I seek your help please? How did you resolve it? https://stackoverflow.com/questions/71612438/type-mismatch-in-from-address-of-a-outlook-mailbox-using-python – The Great Mar 25 '22 at 05:36