Search code examples
pythonmime-typessendmailsmtplib

How to send Attachments to Thunderbird when sending email using MIME in python?


I am trying to send emails from Python using MIME, Emails are working fine as well as Attachments also displayed on web email, but doesn't appear in Email Client like Thunderbird.

This is my code I have written

#!/usr/bin/python
import smtplib
from smtplib import SMTPException
import base64

filename = "ticketexport.csv"

fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) 

sender = 'erp@at.biz'
receivers = ["shravya@at.biz"]

marker = "AUNIQUEMARKER"

body ="""
LO CUSTOMER SUPPORT TICKETS.
"""

part1 = """From: AT <erp@atc.erp>
To: SS<shravya@at.biz>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)


part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
   smtpObj.login('erp@at.biz', 'jklO4d')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException as e:
   print(e)
   print "Error: unable to send email"

Any help would definitely mean a lot. I am so close to this.


Solution

  • Close -- the MIME encoding rules are quite picky.

    In part1, there needs to be an empty line between the Content-Type and the first marker.

    And in part3, the Content-Type should be application/octet-stream. That section is not multipart.