Search code examples
pythonpython-3.xemailpywin32win32com

What's mistake I do in order to send mail with Python


Hi I've a problem if run this code in only one file work.

import win32com.client as win32

outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)

mail.To='[email protected]'
mail.Subject='Message subject'
mail.Body='Message body'

mail.Send()

But now I need to split in order to have a funciton, so I did this.

mailCode.py

import win32com.client as win32

class multipleSendByMail:
    outlook=win32.Dispatch('outlook.application')
    mail=outlook.CreateItem(0)

    def multipleSendMail(self, destMail, msg, subject):
        for i in destMail:
            self.mail.To=destMail #'[email protected]'
            self.mail.Subject=subject #'Message subject'
            self.mail.Body=msg #'Message body'
    
            self.mail.Send()
    return True

main.py

from mailCode import *

sendMail = multipleSendByMail
destMail = ["[email protected]", "[email protected]"]
msg = "Messaggio"
subject = "Oggetto"
ret = sendMail.multipleSendMail(destMail, msg, subject)

But I've got this error:

ret = sendMail.multipleSendMail(destMail, msg, subject)
TypeError: multipleSendMail() missing 1 required positional argument: 'subject'

So I try to modify the main like this:

main.py

from mailCode import *

sendMail = multipleSendByMail()
destMail = ["[email protected]", "[email protected]"]
msg = "Messaggio"
subject = "Oggetto"
ret = sendMail.multipleSendMail(destMail, msg, subject)

But I've got this error:

Traceback (most recent call last):
File "C:/Users/myPath/mailSender/main.py", line 7, in <module>
    ret = sendMail.multipleSendMail(destMail, msg, subject)
  File "C:\Users\myPath\mailSender\mailCode.py", line 9, in multipleSendMail
    self.mail.To=i
  File "C:\tools\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 549, in __setattr__
    self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Eccezione.', (4096, 'Microsoft Outlook', "L'elemento è stato spostato o eliminato.", None, 0, -2147221238), None)

The error is in italian and say the exception that "The element has been moved or removed"

What's wrong? I think is a basic error but I can't see right now?


Solution

  • Resolved.

    destMail = ["[email protected]", "[email protected]"]

    need to be: destMail = "[email protected]; [email protected]"