5

Typically, sending a message with attachments is performed like this in python.

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(msg, 'html'))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string()) # The problem is here
    smtp.close()

However, I cannot perform that since the part to be signed with ꜱᴍɪᴍᴇ is only the body and attachments, not all metadata.

In such situation, I would need to split message and Metadata. However, I still need to use email.mime.multipart and email.mime.application`` for constructing attachments metadata (while excluding other metadata)

So how to create an ʜᴛᴍʟ e‑mail with attachments while still using ʜᴛᴍʟ formatting and attachments ?

user2284570
  • 2,891
  • 3
  • 26
  • 74

0 Answers0