Search code examples
pythonemailmime-typesthunderbird

Thunderbird "size unknown" attachment when sent with python


When I sent email with an attachment using python code below, although the attachment can be downloaded, it will say size unknown next to the attachment, and if I forward that email, the attachment is not in forwarding email, This seemed to be a problem specific to Thunderbird(60.5.2 (32-bit)), but since our company is entirely on TB, I'll need to fix the python code to make it compatible with TB.

I have played with the raw string of the source from "view source" in TB by comparing the source of a email attachment sent within TB which would work, but to no avail.

PS: found related bug tracker in mozilla for reference: https://bugzilla.mozilla.org/show_bug.cgi?id=548507

import os
import smtplib

from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import formataddr
from email.utils import parseaddr

sender = "from@gmail.com"
to_address = ["to@gmail.com"]
subject = "Test subject"
body = "Test body"
title = "title"

attach_files = ['c:\\dummy.pdf']

host = 'localhost.com'
user = 'user@mail.com'
password = 'password'

msg_root = MIMEMultipart('related')
addr = '{} <{}>'.format(title, sender)
name, address = parseaddr(addr)
msg_root['From'] = formataddr((
    Header(name, 'utf-8').encode(),
    address .encode('utf-8') if isinstance(address , unicode) else address))

msg_root['To'] = ','.join(to_address)
msg_root['Subject'] = Header(subject, 'utf-8')
msg_text = MIMEText(body, 'html', 'utf-8')
msg_root.attach(msg_text)

for index, attach_file in enumerate(attach_files, start=1):
    with open(attach_file, 'rb') as attach_obj:
        attach = MIMEApplication(attach_obj.read(),
                                 _subtype="pdf",
                                 name=os.path.basename(attach_file))
        attach.add_header('Content-Disposition', 'attachment',
                          filename=os.path.basename(attach_file))
        msg_root.attach(attach)

connection = smtplib.SMTP_SSL(host=host, timeout=5)
try:
    connection.login(user=user, password=password)
    connection.sendmail(user, all_address, msg_root.as_string())
finally:
    connection.quit()

I can Accept any answer as long as: when forwarding a email with attachment that's send via Python, the attachment from that email is still included within TB(recent version 60+).

Expected result: a file size next to the attachment, and forwarding the attachment email will also include the attachment.


Solution

  • Use 'mixed' instead of 'related'

    msg_root = MIMEMultipart('mixed')
    

    You will see size next to attachement, and attachement will be forwarded.


    Tested on TB 60.7.2 (64-bit) / Linux Mint 19.1