0

I have a Python 3 script that uses MIMEMultipart to send an email with a .xlsx file it has generated attached. I used to use an identical script on Py2 to send the same generated file, the only difference being that the Py2 script collected info from MySQL to create the .xlsx and the Py3 script uses PostgreSQL instead.

msg = MIMEMultipart('alternative')
msg.attach(MIMEText("""HTML stuff""", 'html'))

with open(analysis_file, "rb") as fil:
  msg.attach(MIMEApplication(
                    fil.read(),
                    Content_Disposition='attachment; filename="%s"' % os.path.basename(analysis_file),
                    Name=os.path.basename(analysis_file)
                ))

msg['Subject'] = "SUBJECT"
msg['From']="Me <me@me.com>"
msg['To']= "You <you@you.com>"

server.sendmail(FROMADDR, ["you@you.com"], msg.as_string())

When I switched to the Py3 version of the script, however, the attachment stopped showing up on Microsoft's mail.live. The paperclip symbol that says a message has an attachment still appears, but I can't find it.

--EDIT:

If I set up automatic forwarding to a Gmail account, the .xlsx attachment shows up normally there; however, if I forward it manually it doesn't.

Pedro Carvalho
  • 565
  • 1
  • 6
  • 26

2 Answers2

7

Changing

msg = MIMEMultipart('alternative')

to

msg = MIMEMultipart('html')

fixed it.

Pedro Carvalho
  • 565
  • 1
  • 6
  • 26
0

Do me a favor and test if it works with yagmail. For doing HTML/attachments stuff I think it can really be useful: default is sending things in HTML, and attachments can just be done by pointing to the path.

All the code:

import yagmail
yag = yagmail.SMTP('me@me.com', 'password')
yag.send("you@you.com", "SUBJECT", analysis_file)

The third field in send is contents, which can be a list of strings or just a string. If the string can be loaded as file, it will simply be attached.

For more info, check out the github page. Mind you, I'm the developer/maintainer.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160