Python Unicode问题-如何使用文本文件作为电子邮件主体?



真是惊喜另一个有Unicode问题的人。

我的文本被复制到我的电子邮件中,但只有在被无数次编码为utf-8之后-即使这样,它也与50/50的乱码混合在一起。

在过去,我通过使用路径库编码来避免这种麻烦,但在这里似乎不可能。我认为这对你们来说是最重要的代码。
#Write info to text file
with io.open(f'today.txt', "a", encoding = 'utf-8') as wf:
wf.write(str(today) + 'n')
wf.write(item + 'n')
wf.write(text + 'nn')
wf.write(urlbuff + href + 'nnn')
#Store text for e-mail use
with io.open(f'today.txt', "r+", encoding = 'utf-8') as nwf:
text_to_mail = str(nwf.readlines())
text_mail = text_to_mail.encode('utf-8', 'strict')

我的text_mail输出如下所示:

b'['2021-01-22 ', '财富税','财富税不是完美的,但不是世界末日','n'

如果我不使用所有单独的编码命令,我得到ascii错误和没有输出。我怎样才能解决这个问题,并确保它不会再发生在我身上?我相信一定有比我一直在尝试的更干净、更明智的解决办法。我正在使用smtplib发送电子邮件。

我知道有很多代码你看不见,但我希望这里有足够的。

感谢您的评论,我将with语句更改为:

with io.open(f'today.txt', "r") as nwf:
text_mail = nwf.read()

我还必须更改pc的AppData目录中的smtplib文件,以便一些ascii .encode()语句使用.encode('utf-8')代替。我做了如下修改:

self.putcmd("data")
(code, repl) = self.getreply()
if self.debuglevel > 0:
self._print_debug('data:', (code, repl))
if code != 354:
raise SMTPDataError(code, repl)
else:
if isinstance(msg, str):
msg = _fix_eols(msg).encode('ascii')

:

self.putcmd("data")
(code, repl) = self.getreply()
if self.debuglevel > 0:
self._print_debug('data:', (code, repl))
if code != 354:
raise SMTPDataError(code, repl)
else:
if isinstance(msg, str):
msg = _fix_eols(msg).encode('utf-8')

如果有人需要自己做这个搜索'ascii',改变"msg = _fix_eols(msg).encode('ascii')"从上面的陈述来看,我认为有两个。我不完全了解上述更改的所有可能含义,因此另一个修复可能会更好。

最新更新