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?