0

I am using How to send email attachments? as a basis to try and send an email with and without an attachment using python and have ended up with this code:

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):
    assert isinstance(send_to, list)

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

    msg.attach(MIMEText(text))

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


    server = smtplib.SMTP_SSL('smtp.pobox.com', 465)
    server.login('<username>', '<password>')
    server.sendmail(send_from, send_to, msg.as_string())
    server.close()

send_mail("<username>",["<username>"],"subject","text",["D:\\Desktop\\Python Test\\Logfile.txt"]) # with attachment
#send_mail("<username>",["<username>"],"subject","Text") # without attachment

which appears to send an email with and without attachment depending on the last two lines of the code.

The problem is that with this line of code msg = MIMEMultipart('html') the email received does not show the paperclip attachment icon even if it contains an attachment in the email. So, regardless of whether the email contains an attachment, there is no paperclip attachment icon.

If however, I change this to msg = MIMEMultipart('') I get a paperclip attachment icon on all emails even if they dont contain an attachment.

Does anyone know how I can fix this so that the paperclip attachment icon shows when there is an attachment and not when there isn't one?

cosmarchy
  • 686
  • 3
  • 9
  • 21
  • It may help to specify a mimetype for the attachment - [example](https://stackoverflow.com/a/63538330/5320906) – snakecharmerb Mar 11 '22 at 10:07
  • Tried adding code `mimetypes.guess_type(f)` as the attachment wont always be a specific type but I still get the same problem. – cosmarchy Mar 12 '22 at 15:04

0 Answers0