我正在尝试使用Python 3.3发送基本电子邮件。我在这里遵循第一部分代码:
https://docs.python.org/3.3/library/email-examples.html
我的代码如下:
def emailCurrentRankings(recipientEmail):
fp = open('rankings.txt', 'rb')
msg = MIMEText(fp.read())
fp.close()
sender = 'bclayman@gmail.com'
msg['Subject'] = 'CSA Rankings'
msg['From'] = sender
msg['To'] = recipientEmail
s = smtplib.SMTP('localhost')
s.sendmail(sender, [recipientEmail], msg.as_string())
s.quit()
我的主要功能如下调用此方法:
emailCurrentRankings('bclayman@gmail.com')
我可以告诉的唯一区别是,我在第二行使用了“ rankings.txt”而不是文本文件。我尝试了两者,并得到相同的错误消息:
Traceback (most recent call last):
File "helpfulFunctions.py", line 128, in <module>
main()
File "helpfulFunctions.py", line 120, in main
emailCurrentRankings('bclayman@gmail.com')
File "helpfulFunctions.py", line 106, in emailCurrentRankings
msg = MIMEText(fp.read())
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/email/mime/text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'bytes' object has no attribute 'encode'
当我在Google上四处搜寻时,似乎需要进行一些身份验证(对我来说,它可以从给定的电子邮件中发送)。但是他们在为我的代码建模的最基本的示例中没有提到这一点...
有什么想法让我误入歧途吗?
谢谢,
克莱曼
最佳答案
尝试在不使用二进制格式的情况下打开文件。
也许像-
fp = open('rankings.txt', 'r')