Để gửi email với nội dung hỗn hợp, cần đặt tiêu đề Content-type thành multipart/mixed. Sau đó, các phần văn bản và đính kèm có thể được chỉ định trong boundaries (ranh giới).
Một boundary bắt đầu bằng hai gạch nối theo sau là một số duy nhất, không được xuất hiện trong phần thông điệp của email. Một boundary cuối cùng biểu thị phần cuối cùng của email cũng phải kết thúc bằng hai gạch nối.
Các tệp đính kèm nên được mã hóa bằng hàm pack("m") để có mã hóa base64 trước khi truyền.
Ví dụ
Ví dụ sau gửi tệp /tmp/test.txt như một đính kèm. Hãy thử một lần:
#!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Đọc tệp và mã hóa thành định dạng base64 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. """ # Định nghĩa các tiêu đề chính part1 = """From: From PersonTo: To Person Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Định nghĩa phần hành động thông điệp part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body, marker) # Định nghĩa phần đính kèm 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"