- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sending Attachments as an E-mail using Python
To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.
Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.
Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once −
#!/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 = 'firstname.lastname@example.org' reciever = 'email@example.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person <firstname.lastname@example.org> To: To Person <email@example.com> 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"
- Sending an HTML e-mail using Python
- What is an Electronic Mail (E-Mail)?
- How should I validate an e-mail address in Android using Kotlin?.
- How should I validate an e-mail address in Android?
- Explain the E-Mail Format in Computer Network.
- Sending an HTML Message using Perl
- Sending an Attachment with email using Perl
- How to get the Android device's primary e-mail address?
- Sending an itab to SAP Spool using ABAP method
- Send mail from your Gmail account using Python
- What is the difference between letter, memo, e-mail, texting and formal writing?
- Sending a Plain Message using Perl
- Sending HTTP error code using Express.js
- Sending an Intent to browser to open specific URL using Kotlin.