使用 smtplib 和 MIMEText 在 python 脚本中发送电子邮件,但收到编码错误
Sending an email in a python script using smtplib and MIMEText, but recieving an encoding error
我正在尝试编写一个 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()
目前,运行 这给我的错误是:
文件 "server.py",第 43 行,在 testServer 中
msg = MIMEText(fp.read())
文件 "C:\Users3255\AppData\Local\Programs\Python\Python36\lib\email\mime\text.py",第 34 行,在 init 中
_text.encode('us-ascii')
AttributeError: 'bytes' 对象没有属性 'encode'
但是,我已经尝试将编码从 ascii 更改为 unicode 或 UTF-8,但它仍然给我上述引用 ascii 的错误...
对此是否有简单的解决方案,或其他更简单的发送电子邮件的方法?谢谢!
为了 MIMEText()
正确处理来自 fp
的读取文本,您应该尝试以读取模式(即使用 'r'
)而不是二进制读取模式打开文件。
我正在尝试编写一个 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()
目前,运行 这给我的错误是:
文件 "server.py",第 43 行,在 testServer 中 msg = MIMEText(fp.read()) 文件 "C:\Users3255\AppData\Local\Programs\Python\Python36\lib\email\mime\text.py",第 34 行,在 init 中 _text.encode('us-ascii') AttributeError: 'bytes' 对象没有属性 'encode'
但是,我已经尝试将编码从 ascii 更改为 unicode 或 UTF-8,但它仍然给我上述引用 ascii 的错误...
对此是否有简单的解决方案,或其他更简单的发送电子邮件的方法?谢谢!
为了 MIMEText()
正确处理来自 fp
的读取文本,您应该尝试以读取模式(即使用 'r'
)而不是二进制读取模式打开文件。