TypeError: string payload expected: <class 'list'> Error when trying to send an e-Mail witth an zip file attaced in Python 3.9.6

Viewed 70

I use the following code (extract) for sending an e-mail:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
smtpServer = "(Servername)"
smtpPort = (Portnumber)
smtpUsername = "(SMTP Username)" 
smtpPassword = "(Password)" 
sender = "(Username)" 
reciever = "(Username)"
subject = "(subject)"
body = "Text"
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = reciever
body = MIMEText(body, 'plain')
msg.attach(body)
msg = MIMEBase('application', 'octet-stream')
attach_file = open(zipfilename, 'rb')
payload = MIMEApplication(zipfilename)
payload.set_payload(attach_file.read(), 'rb')
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=zipfilename)
msg.attach(payload)
smtpObj = smtplib.SMTP(smtpServer, smtpPort)
smtpObj.set_debuglevel(1)
smtpObj.starttls()
smtpObj.sendmail(sender, reciever, msg.as_string())
attach_file.close()
smtpObj.close()

I got the following error message:

Traceback (most recent call last):
  File "E:\Data\testmail.py", line 31, in <module>
    smtpObj.sendmail(sender, reciever, msg.as_string())
  File "E:\Program\Python\3.9.6\lib\email\message.py", line 158, in as_string
    g.flatten(self, unixfrom=unixfrom)
  File "E:\Program\Python\3.9.6\lib\email\generator.py", line 116, in flatten
    self._write(msg)
  File "E:\Program\Python\3.9.6\lib\email\generator.py", line 181, in _write
    self._dispatch(msg)
  File "E:\Program\Python\3.9.6\lib\email\generator.py", line 218, in _dispatch
    meth(msg)
  File "E:\Program\Python\3.9.6\lib\email\generator.py", line 239, in _handle_text
    raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: <class 'list'>

I have already searched in various sources (e.g. TypeError: string payload expected: <class 'bytes'>, https://github.com/Pylons/pyramid_mailer/issues/24, ...), but the hints I found weren't suitable. What is the reason for the failure? What can I do?

0 Answers
Related