我正在尝试编写一个发送电子邮件的python脚本。我的代码目前看起来像:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.action_chains import ActionChains
from urllib.request import urlopen
from html.parser import HTMLParser
import smtplib
from email.mime.text import MIMEText
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path='C:\geckodriver-v0.18.0-win64\geckodriver.exe')
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = driver
def testServer(self):
me = 'person@gmail.com'
you = 'person@gmail.com'
with open("testfile.txt", 'rb') as fp:
msg = MIMEText(fp.read())
msg['Subject']= 'Testing email'
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
driver.close()
if __name__ == "__main__":
unittest.main()
目前,运行此操作会给我一个错误:
在testServer中的第43行文件“server.py” msg = MIMEText(fp.read()) 文件“C:\ Users \ 663255 \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ email \ mime \ text.py”,第34行, init _text.encode( 'US-ASCII') AttributeError:'bytes'对象没有属性'encode'
但是,我尝试将编码从ascii更改为unicode或UTF-8,它仍然给我上面的错误引用ascii ...
是否有简单的解决方案,或者发送更简单的电子邮件的其他方法?谢谢!
答案 0 :(得分:1)
为了让MIMEText()
正确处理来自fp
的读取文本,您应该尝试以读取模式打开文件(即使用'r'
)而不是二进制读取模式。