使用smtplib发送文件时更改stdout格式 - python2.7

use*_*315 7 python python-2.7

如果从文件中读取电子邮件正文,则Python2.7输出格式无法获得预期.user_info.txt是由另一个作业生成的文件,其中包含用户的所有详细信息.user_info.txt的输出格式很好.将该文件作为电子邮件发送的地方,输出格式完全改变.从文件中读取时我做错了吗?有人可以帮我这个吗?

脚本:

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart('alternative')
msg['Subject'] = "User Info"

"""Create the body of the message"""
open_file = open('/tmp/user_info.txt')
user_info = MIMEText(open_file.read().encode("utf-8"), 'plain', 'utf-8')
msg.attach(user_info)
open_file.close()

"""Send the message via gmail SMTP server."""
server = smtplib.SMTP('smtp-relay.gmail.com', 587)
server.sendmail("admin", "user1@test.com", msg.as_string())
server.quit()
Run Code Online (Sandbox Code Playgroud)

示例user_info.txt

user_name  Department_no ID          detail1     detail2 


aaaa          4         13           25088       32.000000

bbbbbbb       5         17           33280       42.000000

ccccccccccc   3          9           16896       22.000000

dddddd        5         17           33280       42.000000

eeeeeeeee     5         14           27136       36.000000
Run Code Online (Sandbox Code Playgroud)

电邮输出:

user_name Department_no ID detail1 detail2

aaaa 4 13 25088 32.000000

bbbbbbb 5 17 33280 42.000000

ccccccccccc 3 9 16896 22.000000

dddddd 5 17 33280 42.000000

eeeeeeeee 5 14 27136 36.000000

请查看电子邮件截图:

电子邮件

sto*_*vfl 3

问题 ...输出格式完全改变。从文件中读取时我做错了什么吗

使用 Python:3.4.2 和 2.7.9 进行测试,您的代码和给定的user_info.txt格式没有失败。
可以接收相同格式的user_info.txt 。
所以,你没有做错什么


在不发送电子邮件的情况下,尝试以下操作来验证您使用的email.mime module作品是否符合预期。输出应该没问题

result = user_info.get_payload(decode=True).decode('utf-8','ignore')
print(result)
Run Code Online (Sandbox Code Playgroud)

一般来说,不能保证电子邮件的接收者使用相同的字体、大小或相同的环境。

如果您想确定,数据布局看起来与使用Portabel 文档格式相同。