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

Python SMTP function sending .txt file as .bin file-type

当调用下面的 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()