Computer >> Máy Tính >  >> Lập trình >> Python

Gửi tệp đính kèm dưới dạng e-mail bằng Python

Để gửi e-mail có nội dung hỗn hợp, bạn phải đặt Loại nội dung tiêu đề thành nhiều phần / hỗn hợp . Sau đó, các phần văn bản và phần đính kèm có thể được chỉ định trong ranh giới .

Ranh giới được bắt đầu bằng hai dấu gạch nối theo sau là một số duy nhất, không thể xuất hiện trong phần thư của e-mail. Ranh giới cuối cùng biểu thị phần cuối cùng của e-mail cũng phải kết thúc bằng hai dấu gạch nối.

Các tệp đính kèm phải được mã hóa bằng pack ("m") có chức năng mã hóa base64 trước khi truyền.

Ví dụ

Sau đây là ví dụ gửi tệp /tmp/test.txt dưới dạng tệp đính kèm. Hãy thử một lần -

#!/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 Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.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"