मिश्रित सामग्री के साथ एक ई-मेल भेजने के लिए Content-type हेडर को multipart/mixed पर सेट करना आवश्यक है। फिर, टेक्स्ट और अटैचमेंट सेक्शन को बाउंड्रीज़ के भीतर निर्दिष्ट किया जा सकता है।
एक बाउंड्री दो हाइफ़न के बाद एक अद्वितीय संख्या से शुरू होती है, जो ई-मेल के संदेश भाग में प्रकट नहीं हो सकती। ई-मेल के अंतिम खंड को दर्शाने वाली एक अंतिम बाउंड्री भी दो हाइफ़न के साथ समाप्त होनी चाहिए।
संलग्न फ़ाइलों को ट्रांसमिशन से पहले base64 एन्कोडिंग के लिए pack("m") फ़ंक्शन के साथ एन्कोड किया जाना चाहिए।
उदाहरण
निम्नलिखित उदाहरण है, जो एक फ़ाइल /tmp/test.txt को अटैचमेंट के रूप में भेजता है। इसे एक बार आज़माएं −
#!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) # base64 sender = 'webmaster@tutorialpoint.com' reciever = 'amrood.admin@gmail.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From PersonTo: To Person Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Define the message action 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('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email" except Exception: print "Error: unable to send email"