在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP)

2023-07-03Python开发问题
11

本文介绍了在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我使用 Python 模块 MimeWriter 构造消息和 smtplib 发送邮件构造消息是:

文件 msg.txt:----------------------内容类型:多部分/混合;来自:我<me@abc.com>至:me@abc.com主题:主题内容类型:text/plain;charset=utf-8主题

我使用下面的代码发送邮件:

导入 smtplibs=smtplib.SMTP('smtp.abc.com')toList = ['me@abc.com']f=open('msg.txt') #高于 msg.txt 文件中的 msg味精=f.read()f.close()s.sendmail('me@abc.com',toList,msg)

我的邮件正文正确,但主题不正确,

主题:一些垃圾字符主题 <- 正文是正确的.

请建议?有没有办法指定用于主题的解码,为身体指定.如何正确解码主题?

解决方案

来自 http://docs.python.org/library/email.header.html

从 email.message 导入消息从 email.header 导入标头味精=消息()msg['Subject'] = Header('主题', 'utf-8')打印 msg.as_string()

<块引用>

主题:=?utf-8?b?5Li76aGM?=

更简单:

from email.header import Headerprint Header('主题', 'utf-8').encode()

<块引用>

=?utf-8?b?5Li76aGM?=

I am using Python module MimeWriter to construct a message and smtplib to send a mail constructed message is:

file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<me@abc.com>
to: me@abc.com
subject: 主題

Content-Type: text/plain;charset=utf-8

主題

I use the code below to send a mail:

import smtplib
s=smtplib.SMTP('smtp.abc.com')
toList = ['me@abc.com']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('me@abc.com',toList,msg)

I get mail body correctly but subject is not proper,

subject: some junk characters

主題           <- body is correct.

Please suggest? Is there any way to specify the decoding to be used for the subject also, as being specified for the body. How can I get the subject decoded correctly?

解决方案

From http://docs.python.org/library/email.header.html

from email.message import Message
from email.header import Header
msg = Message()
msg['Subject'] = Header('主題', 'utf-8')
print msg.as_string()

Subject: =?utf-8?b?5Li76aGM?=

more simple:

from email.header import Header
print Header('主題', 'utf-8').encode()

=?utf-8?b?5Li76aGM?=

这篇关于在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11