是啥导致我的“test.txt”文件从 Python 发送到我的 gmail 帐户时,当我在我的电子邮件收件箱中收到它时,它会显示为“无标题”?

Posted

技术标签:

【中文标题】是啥导致我的“test.txt”文件从 Python 发送到我的 gmail 帐户时,当我在我的电子邮件收件箱中收到它时,它会显示为“无标题”?【英文标题】:What is causing my 'test.txt' file being sent from Python to my gmail account to come across as "Untitled" when I receive it in my email inbox?是什么导致我的“test.txt”文件从 Python 发送到我的 gmail 帐户时,当我在我的电子邮件收件箱中收到它时,它会显示为“无标题”? 【发布时间】:2021-05-29 23:17:40 【问题描述】:

我正在通过 python 程序发送一个名为test.txt 的文件作为下面的附件。它成功发送,但是当我在我的 Gmail 收件箱中收到它时,附件显示 Untitled 而不是 text.txt。我在下面有我的电子邮件代码块,它看起来是正确的。有什么建议吗?

# Setup the email
mail_content = '''Hello,
The attached document contains the results of the file scan.
Please contact the IT Help Desk if you have any questions.
Thank You!!!
'''
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'david.txt'
# attach_file_name = file_name
attach_file = open(attach_file_name, 'rb')  # Open the file as binary mode

# Setup the Payload
payload = MIMEBase('application', 'octate-stream')
payload.set_payload(attach_file.read())
encoders.encode_base64(payload)  # encode the attachment
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)

# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587)  # use gmail with port
session.starttls()  # enable security
session.login(sender_address, sender_pass)  # login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

我收到的电子邮件的屏幕截图:

【问题讨论】:

【参考方案1】:

因为拼写很重要。不是“octate-stream”,而是“octet-stream”,也不是“Content-Decomposition”,而是“Content-Disposition”。

【讨论】:

谢谢!我今天盯着那个代码看了几个小时,没有看到。它现在按预期工作。 :)

以上是关于是啥导致我的“test.txt”文件从 Python 发送到我的 gmail 帐户时,当我在我的电子邮件收件箱中收到它时,它会显示为“无标题”?的主要内容,如果未能解决你的问题,请参考以下文章

java里的目录是啥意思如File f=new File("d:\\","test.txt"); 这里的f是目录么,还是类似c中的指针的东

是啥导致 Visual Studio 2017 中的文件名为空

从文件TEST中读出字符并写入TEST1里,要求均附加错误检查--p209_5

我的应用程序从“有一个或多个问题”变为“已完成处理”,而我没有碰它。是啥导致了这种变化?

Tortoise SVN Merge 特定版本

关于“ echo Test > Test.txt” [重复]