使用Python将附件作为电子邮件发送
要发送包含混合内容的电子邮件,需要将Content-type标头设置为multipart/mixed。然后,可以在border中指定文本和附件部分。
边界以两个连字符开头,后跟一个唯一编号,该编号不能出现在电子邮件的邮件部分中。表示电子邮件最后部分的最后边界也必须以两个连字符结尾。
传输前,应使用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 = '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"