Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ส่งอีเมลพร้อมไฟล์แนบ (Attachments) ใน Python

การส่งอีเมลที่มีเนื้อหาประกอบ (mixed content) ต้องตั้ง header Content-type เป็น multipart/mixed จากนั้น ส่วนข้อความและไฟล์แนบสามารถระบุได้ภายใน boundaries

Boundary เริ่มต้นด้วยขีดกลับสองครั้งตามด้วยหมายเลขเฉพาะที่ไม่ควรปรากฏในส่วนข้อความของอีเมล Boundary สุดท้ายที่ระบุส่วนสุดท้ายของอีเมล ต้องลงท้ายด้วยขีดกลับสองครั้งเช่นกัน

ไฟล์แนบควรเข้ารหัสด้วยฟังก์ชัน pack("m") เพื่อให้ได้ base64 encoding ก่อนส่ง

ตัวอย่างโค้ด

ตัวอย่างต่อไปนี้ส่งไฟล์ /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 Person 
To: 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"