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

时间:2019-03-19 21:30:24

标签: linux python-3.x smtplib pathlib

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

1 个答案:

答案 0 :(得分:1)

文件发送时没有扩展名,因为文件名被解释为“ 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()