我正在尝试使用电子邮件模块发送电子邮件。我正在通过读取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()
答案 0 :(得分:1)
“无法解析”旁边的单引号看起来像是Unicode智能单引号,而不是ASCII撇号。
Python mime模块因此使用Base64编码对其进行编码,因为它超出了ASCII的32-128范围。
您正在使用哪个文本编辑器,因为您可能想尝试替代方法?