使用 MIMEText 读取文本文件时出现奇怪的不需要的 header

Strange unwanted header when reading text file with MIMEText

我正在编写一个程序来读取文本文件。我已经设法让它工作了,但是我得到了一个奇怪的 header 我不想要的。

文本文件名为“SixMonthTextFile.txt,用记事本保存在windows。

我得到的不需要的 header 是 -

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0

Content-Transfer-Encoding: 7bit

Body of text read from file here

我已经尝试删除前 3 行,但没有用,只会导致新问题。关于它为什么会发生以及更重要的是如何阻止它的任何想法?

我的密码是

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#Read an external text file for body of message
fp = open('SixMonthTextFile.txt', 'r')
SixMonthMessage = MIMEText(fp.read())
fp.close()

print(SixMonthMessage)

我得到的结果是

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

We would like to remind you that it has been six months
since your last service and its time for a precautionary service
since your equipment needs regular servicing to remain reliable.

Please reply to this email to book your FREE appointment.
[Finished in 0.4s]

我只想要文本文件中的原始文本,因为它将进入电子邮件 body。

关于为什么我会收到奇怪的不需要的额外内容 header 以及如何摆脱它有什么想法吗?

所以我尝试了 stovfl 的建议,并尝试将 get_payload(),'3\n' 添加到 MIMEText(fp.read() 语句中,它删除了不需要的 header 但也弄乱了文本文件的格式,结果仍然无法使用。

我换个角度解决了这个问题,并将 fp = open() 等替换为

打开('SixMonthTextFile.txt','r')作为文件: SixMonthTextFile = file.read()

'''

这给了我文本,然后可以按照文本文件中的格式使用这些文本以插入到电子邮件中。

def sendsixmonthemail(address, EmailTo):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#Read an external text file for body of message
with open('SixMonthTextFile.txt', 'r') as file:
    SixMonthTextFile = file.read()



host="smtp.gmail.com"
email="myemailaddress@gmail.com"
password = "123456786"

from_addr='myemailaddress@gmail.com'
to_addr=EmailTo
reply_address = "myemailaddress@gmail.com"

msg=MIMEMultipart()
msg['From']=from_addr
msg['To'] = to_addr
msg['reply-to'] = "myemailaddress@gmail.com"
msg['subject']='FREE 6 month Service Reminder for' + " " + address

#Data read from Text File
body= str(SixMonthTextFile)


msg.attach(MIMEText(body,'plain'))

mail=smtplib.SMTP_SSL(host,465)
mail.login(email,password)
text=msg.as_string()

mail.sendmail(email,to_addr,text)
mail.quit()

我之所以希望能够轻松编辑包含在电子邮件中的消息,是因为这样我们就不必在每次要将任何内容包含在电子邮件中时都重新编写程序。对于只收到年度提醒但收到不同消息的客户,它还可以更轻松地复制和修改流程。