使用 Python 发送电子邮件附件
要发送包含混合内容的电子邮件,需要将内容类型报头设置为multipart/mixed。然后,可以在边界内指定文本和附件部分。
边界以两个连字符及其后唯一数字开头,该数字不能出现在电子邮件的邮件部分中。表示电子邮件最后一个部分的最终边界也必须以两个连字符结尾。
应使用pack("m") 函数对附加文件进行编码,以在传输前进行 base64 编码。
示例
以下是将文件/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 = '[email protected]' reciever = '[email protected]' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person <[email protected]> To: To Person <[email protected]> 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"
广告