pythonemailattachmentemail-attachmentsmime

Setting File Type for Emailed Attachments


A Python script for sending email with attachments is working, but all attachments, if any, are arriving as .eml files rather than as jpg, pdf, txt, etc. They do open correctly, but I would prefer that they bear their actual name and type. Although I made a minor change for Python 3 ( attach( changed to add_attachment( ), it did work for me on Python 2.7.

Also, I keep coming across references that set_payload has been deprecated, but I can't see what to use instead.

# Attach any files
files = '''/Users/Mine/Desktop/RKw.jpeg\n/Users/Mine/Desktop/PG_2022.pdf'''.splitlines()
for file in files:
    attachment = open(file, "rb")
    part = MIMEBase("application", "octet-stream")
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename= {file.split('/')[-1]}")
    msg.add_attachment(part)

Solution

  • You can pass options to add_attachment for the filename and the content type amongst other options for the attached file.

    def get_ctype(filepath):
        ctype, encoding = mimetypes.guess_type(filepath)
        if ctype is None or encoding is not None:
           ctype = 'application/octet-stream'
        return ctype
    
    # Attach any files
    files = '''/Users/Mine/Desktop/RKw.jpeg\n/Users/Mine/Desktop/PG_2022.pdf'''.splitlines()
    for file in files:
        attachment = open(file, "rb")
        ctype = get_ctype(file)
        maintype, subtype = ctype.split('/', 1)
    
        msg.add_attachment(
            attachment.read(),
            maintype=maintype,
            subtype=subtype,
            filename=file.split('/')[-1],    
        )