首页 > 解决方案 > Python电子邮件模块无法处理引号

问题描述

我正在尝试使用电子邮件模块发送电子邮件。我通过从txt文件中读取来获取电子邮件的文本正文。一切正常,直到我在我的文本文件中添加引号(双引号和单引号),整个事情都搞砸了

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

text1 = str(open('text1.txt').read())
msg1 = MIMEMultipart()
msg1.attach(MIMEText(text1))
print(text1)
print(msg1)

text2 = str(open('text2.txt').read())
msg2 = MIMEMultipart()
msg2.attach(MIMEText(text2))
print(text2)
print(msg2)

结果:

can parse this
Content-Type: multipart/mixed; boundary="===============8027747689981589951=="
MIME-Version: 1.0

--===============8027747689981589951==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

can parse this
--===============8027747689981589951==--

cannot parse this ’
Content-Type: multipart/mixed; boundary="===============8498717586203770272=="
MIME-Version: 1.0

--===============8498717586203770272==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64

Y2Fubm90IHBhcnNlIHRoaXMg4oCZ

--===============8498717586203770272==--

当我从包含引号的文件中读取用户名和密码时,这也是一个问题txt,在这种情况下,我会收到以下错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
    return self.func(*args)
  File "/Users/nathan/Library/Mobile Documents/com~apple~CloudDocs/CEP/Y3/RIPB Offence Booking System/OffenceBookingClasses.py", line 95, in WeeklyEmail
    self.EmailHandler.SendEmail('weekly', identifier='3A')
  File "/Users/nathan/Library/Mobile Documents/com~apple~CloudDocs/CEP/Y3/RIPB Offence Booking System/OffenceBookingClasses.py", line 365, in SendEmail
    self._SubSendEmail(teacher_email, text, attachment_filename)
  File "/Users/nathan/Library/Mobile Documents/com~apple~CloudDocs/CEP/Y3/RIPB Offence Booking System/OffenceBookingClasses.py", line 390, in _SubSendEmail
    server.login(self.fromaddr, self.pw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/smtplib.py", line 720, in login
    initial_response_ok=initial_response_ok)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/smtplib.py", line 629, in auth
    response = encode_base64(initial_response.encode('ascii'), eol='')
UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position [a number is here but I'm removing it in case someone guesses my password from this]: ordinal not in range(128)

str发送电子邮件的代码(如果我只在代码本身中使用变量,这不是问题):

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(self.fromaddr, self.pw)
text = msg.as_string()
server.sendmail(self.fromaddr, toaddr, text)
server.quit()

标签: python-3.xemail

解决方案


“无法解析”旁边的单引号看起来像 Unicode 智能单引号,而不是 ASCII 撇号。

因此,Python mime 模块使用 Base64 编码对其进行编码,因为它超出了 ASCII 的 32-128 范围。

您正在使用哪种文本编辑器,因为您可能想尝试替代方法?


推荐阅读