我正在设置一个脚本,将进入的邮件转发给一组收件人。
这是我现在拥有的:
我从stdin(也就是postfix传递来的方式)读取邮件:
email_in = sys.stdin.read()
incoming = Parser().parse(email_in)
sender = incoming['from']
this_address = incoming['to']
我测试multipart:
if incoming.is_multipart():
for payload in incoming.get_payload():
# if payload.is_multipart(): ...
body = payload.get_payload()
else:
body = incoming.get_payload(decode=True)`
我设置了外发消息:
msg = MIMEMultipart()
msg['Subject'] = incoming['subject']
msg['From'] = this_address
msg['reply-to'] = sender
msg['To'] = "foo@bar.com"
msg.attach(MIMEText(body.encode('utf-8'), 'html', _charset='UTF-8'))
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
这在处理ASCII字符(英文文本)时非常有效,并将其转发。
但是,当我发送非ASCII字符时,它会返回乱码(取决于电子邮件客户端字节或utf-8字符的ASCII表示形式)。
问题可能出在哪里?是在传入方还是传出方?
MIMEText
部分进行编码;它会为你编码,选择适当的字符集。但这并不会改变输出结果。 - Martijn Pieters