Sending an email with attachments

To send messages with attachments, you must create an object instance of the MimeMultipart() class. If there are multiple attachments, these can be built sequentially. In this example, we are attaching two text files to the message:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

message = MIMEMultipart()
message['From'] = Header("Sender", 'utf-8')
message['To'] = Header("Receiver", 'utf-8')
message['Subject'] = Header('Python SMTP', 'utf-8')

message.attach(MIMEText('Python SMTP', 'plain', 'utf-8'))

file1 = MIMEText(open('file1.txt', 'rb').read(), 'base64', 'utf-8')
file1["Content-Type"] = 'application/octet-stream'
file1["Content-Disposition"] = 'attachment; filename="file1.txt"'
message.attach(file1)

file2 = MIMEText(open(‘file2.txt', 'rb').read(), 'base64', 'utf-8')
file2["Content-Type"] = 'application/octet-stream'
file2["Content-Disposition"] = 'attachment; filename="file2.txt"'
message.attach(file2)

In this script we are using the attach() method from MIMEMultipart class for attaching two files with the message. Each file is declared as MIMEText object and defined as application/octet-stream in the Content-Type property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset