使用python脚本发送附件的电子邮件

时间:2014-08-18 06:45:59

标签: python

我使用tutorialspoint.com中提供的代码发送带有附件的电子邮件。代码工作正常,我也收到了电子邮件,但问题是当我上传一个看起来像这样的文本文件:

|Checks|     |Status|        |Remarks|                                                                                           

ECHConnect   checked         The model is completely connected


ECHPenetra   checked         EChPenet: 2436 elements penetrate/touch each other


ECHCharlen   not_checked     

ECHCoincid   checked         No coincident elements


ECHEdgeLen   checked         Shortest edge length = 1.


EMSameNorm   checked         No elements have to be reoriented


EEBeam       checked         34 elements modified according to window settings


Outline      checked         Free edges displayed in green

我收到的文本文件非常混乱了缩进。但我希望与此完全相似。我怎样才能做到这一点?我使用的代码如下:

#!/usr/bin/python

import smtplib
import base64

filename = "/home/hamanda/Desktop/transfer/new_result.txt"

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)

sender = 'harisyam.manda@daimler.com'
reciever ='harisyam.manda@daimler.com' 

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <harisyam.manda@daimler.com>
To: To Person <harisyam.manda@daimler.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, filecontent, 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"

0 个答案:

没有答案