gpt4 book ai didi

python - 通过 Python 发送电子邮件的程序以 "AttributeError: ' str 退出'对象没有属性 'get_content_maintype''"

转载 作者:太空狗 更新时间:2023-10-30 02:49:05 24 4
gpt4 key购买 nike

我有 python 代码,用于发送带附件的电子邮件,我已经归结为:

#!/usr/bin/python
import os, re
import sys
import smtplib

#from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText


SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

sender = 'me@gmail.com'
password = "e45dt4iamkiddingthisisnotmypassword"
recipient = 'he@gmail.com'
subject = 'Python emaillib Test'
message = 'Images attached.'

def main():
msg = MIMEMultipart()
msg['Subject'] = 'Python emaillib Test'
msg['To'] = recipient
msg['From'] = sender

msg.attach('/tmp/images/a.gif')

part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo

session.login(sender, password)

# my_message=msg.as_string()
qwertyuiop=msg
session.sendmail(sender, recipient, qwertyuiop.as_string())

session.quit()

if __name__ == '__main__':
main()

我在运行时遇到这个错误:

Traceback (most recent call last):
File "./abcd.py", line 49, in <module>
main()
File "./abcd.py", line 44, in main
session.sendmail(sender, recipient, qwertyuiop.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 134, in _dispatch
meth(msg)
File "/usr/lib/python2.7/email/generator.py", line 203, in _handle_multipart
g.flatten(part, unixfrom=False)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 125, in _dispatch
main = msg.get_content_maintype()
AttributeError: 'str' object has no attribute 'get_content_maintype'

我认为它与 msg.attach("/tmp/images/a.gif") 有关,但我不确定。不过,问题的根源是 qwertyuiop.as_string()。

最佳答案

问题是 msg.attach() 附加了另一条消息,而不是字符串/文件名。您需要创建一个 MIMEImage 对象并附加它:

# instead of msg.attach('/tmp/images/a.gif')...
fp = open('/tmp/images/a.gif', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msg.attach(msgImage)

示例改编自 here

如果您想要图像以外的类型,请查看 http://docs.python.org/library/email.mime.html .

您在 qwertyuiop.as_string() 行收到错误的原因是在您调用 as_string() 之前不会解析消息。

关于python - 通过 Python 发送电子邮件的程序以 "AttributeError: ' str 退出'对象没有属性 'get_content_maintype''",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9728165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com