【问题标题】:Sending an email in a python script using smtplib and MIMEText, but recieving an encoding error使用 smtplib 和 MIMEText 在 python 脚本中发送电子邮件,但收到编码错误
【发布时间】:2018-01-12 17:59:49
【问题描述】:

我正在尝试编写一个发送电子邮件的 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 中 味精 = MIMEText(fp.read()) init 中的文件“C:\Users\663255\AppData\Local\Programs\Python\Python36\lib\email\mime\text.py”,第 34 行 _text.encode('us-ascii') AttributeError: 'bytes' 对象没有属性 'encode'

但是,我尝试将编码从 ascii 更改为 unicode 或 UTF-8,但它仍然给了我上述引用 ascii 的错误...

是否有一个简单的解决方案,或者另一种发送电子邮件的更简单的方法?谢谢!

【问题讨论】:

  • 可以加行号吗

标签: python email encoding mime smtplib


【解决方案1】:

为了让MIMEText() 正确处理来自fp 的读取文本,您应该尝试以读取模式(即使用'r')而不是二进制读取模式打开文件。

【讨论】:

  • 这行得通,但现在我收到以下错误: ConnectionRefusedError: [WinError 10061] 由于目标机器主动拒绝,无法建立连接
  • 这是否与在代码中没有电子邮件凭据或其他内容的情况下从电子邮件发送电子邮件有关?
  • 这可能是因为localhost 目标上没有运行 SMTP 服务器。 smtplib.SMTP() 函数接受一个标识目标邮件服务器的字符串,因此请务必指定一个有效地址。
  • 我该怎么做?我没有使用 SMTP 的经验,抱歉 =/
  • 是的。你应该看看this link:它描述了如何使用 SMTP 协议使用 Python 发送电子邮件。 “项目:发送会员会费提醒电子邮件”应该对您的案例特别感兴趣。它描述了一种使用gmail SMTP 服务器的方法。
猜你喜欢
  • 2011-09-17
  • 2017-10-10
  • 2021-12-01
  • 2023-02-11
  • 2021-04-26
  • 1970-01-01
  • 2015-09-07
  • 2017-09-20
  • 2013-11-05
相关资源
最近更新 更多