gpt4 book ai didi

linux - Python SMTP 函数将 .txt 文件作为 .bin 文件类型发送

转载 作者:太空狗 更新时间:2023-10-29 12:22:39 26 4
gpt4 key购买 nike

当调用下面的 SMTP 函数时,消息被发送到我的邮箱,但日志文件作为 .bin 文件类型附加。打开时,.bin 文件读取起来就像是 .txt 文件类型一样,但我无法在我的移动设备上打开 .bin 文件,这对我来说是个大问题。有什么方法可以使用原始文件类型将此文件附加到邮件中吗?非常感谢任何反馈。

编辑:当我从 Windows 机器上运行时,文件以其原始文件类型 (.txt) 发送,但当我从 Linux 机器上运行时,文件类型被错误处理。我已经使用 Outlook(首选)和 Gmail 对此进行了测试。 Outlook 将文件识别为 .bin 文件类型,而 Gmail 根本无法识别文件类型。

from pathlib import Path
data_folder = Path("path/to/working/directory")
log_file = Path(data_folder / "log.txt")

def sendmail():

maildate = str(datetime.now().strftime("%m" + "/" + "%d" + "/" + "%Y"))
subjectdate = str("Subject - " + maildate)

import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders

msg = MIMEMultipart()
msg['Subject'] = subjectdate
msg['From'] = 'from@from.com'
msg['To'] = 'to@to.com'

attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(open(log_file, "r").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment, filename=log_file')

msg.attach(attachment)

s = smtplib.SMTP('sender@sender.com')
s.send_message(msg)
s.quit()

最佳答案

发送的文件没有扩展名,因为文件名被解释为“log_file”而不是 log_file 的值。下面的代码按预期工作并将文件正确附加到邮件中。

from pathlib import Path
data_folder = Path("path/to/working/directory")
log_file = Path(data_folder / "log.txt")

def sendmail():

maildate = str(datetime.now().strftime("%m" + "/" + "%d" + "/" + "%Y"))
subjectdate = str("Subject - " + maildate)

import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders

msg = MIMEMultipart()
msg['Subject'] = subjectdate
msg['From'] = 'from@from.com'
msg['To'] = 'to@to.com'

attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(open(log_file, "r").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment, filename="log.txt"')

msg.attach(attachment)

s = smtplib.SMTP('sender@sender.com')
s.send_message(msg)
s.quit()

关于linux - Python SMTP 函数将 .txt 文件作为 .bin 文件类型发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com