Search code examples
linuxpython-3.xsmtplibpathlib

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


When calling the below SMTP function, the message is sent to my mailbox, but the log file is attached as .bin file-type. When opened, the .bin file reads as it would if it were a .txt file-type, but I cannot open .bin files on my mobile device, which is a huge problem for me. Is there any way to attach this file to the message using its original file-type? Any feedback is very much appreciated.

Edit: The file is sent with its original file-type (.txt) when I run this from a Windows machine, but the file-type is mishandled when I run it from a Linux machine. I have tested this with both Outlook (preferred) and Gmail. Outlook recognizes the file as .bin file-type while Gmail does not recognize a file-type at all.

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()

Solution

  • The file sends without an extension because the filename is interpreted as "log_file" instead of the value of log_file. The code below works as expected and attaches the file to the message correctly.

    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()