我正在尝试使用python发送带有.pdf或.html文件作为附件的电子邮件。 如果我发送pdf文件,则以下代码可以正常工作,但是如果我附加html文件,则会收到异常。
def send_mail(app, sub, body, filename=None):
FROM = Config.Email.FROM_ADDRESS
TO = Config.Email.FAIL_RECIPIENTS
sender = Mailer(Config.Email.SMTP_SERVER)
message = Message(From = FROM, To = TO)
message.Subject = sub
message.Html = body
if filename is not None:
if not os.path.exists(filename):
message.Subject = sub + " " + '[Attachment is missing as the file path in invalid.]'
sender.send(message)
return
else:
message.attach(filename)
try:
sender.send(message)
return
except AttributeError:
ctype, encoding = mimetypes.guess_type(filename)
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
fp = open(filename)
attach = MIMEText(fp.read(), _subtype=subtype)
fp.close()
attach.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(filename)
sender.send(message)
return
sender.send(message)
if __name__ == "__main__":
send_mail()
例外:
Traceback (most recent call last):
File "C:/git_workspace/proj/core/common_utils.py", line 65, in send_mail
sender.send(message)
File "C:\Python_VEnv\automation\lib\site-packages\mailer.py", line 124, in send
self._send(server, m)
File "C:\Python_VEnv\automation\lib\site-packages\mailer.py", line 161, in _send
server.sendmail(me, you, msg.as_string())
File "C:\Python_VEnv\automation\lib\site-packages\mailer.py", line 244, in as_string
return self._multipart()
File "C:\Python_VEnv\automation\lib\site-packages\mailer.py", line 349, in _multipart
self._add_attachment(msg, filename, cid, mimetype, content, charset)
File "C:\Python_VEnv\automation\lib\site-packages\mailer.py", line 375, in _add_attachment
msg = MIMEText(content, _subtype=subtype, _charset=charset)
File "C:\Python3\lib\email\mime\text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'bytes' object has no attribute 'encode'
我在这里想念什么?