sendmail.py
上传用户:gyjinxi
上传日期:2007-01-04
资源大小:159k
文件大小:3k
- try: from cStringIO import StringIO
- except: from StringIO import StringIO
- from smtplib import SMTP
- from mimetools import choose_boundary, encode
- from string import split, join, replace, strip
- import mimetypes, os
- from Message import *
- from bobomailrc import *
- from bobomailrc import __version__
- mimetypes.init(["/etc/mime.types", bm_mimetypes])
- def makePart(body, encoding):
- msg = Message(StringIO())
- msg["Content-Transfer-Encoding"] = encoding
- out = StringIO()
- mimetools.encode(StringIO(body), out, encoding)
- msg.body = out.getvalue()
- if encoding == "quoted-printable":
- lines = split(msg.body, "n")
- for i in xrange(len(lines)):
- if lines[i] and lines[i][:5] == 'From ':
- lines[i] = "=%02x" % ord("F") + lines[i][1:]
- msg.body = join(lines, "n")
- return msg
- class SentFailed:
- def __init__(self, e, c, r):
- self.email, self.code, self.reason = e, c, r
- def __repr__(self):
- return str((self.code, self.reason, self.email))
- def sendmail(From, To, Cc=None, Bcc=None, Subject="", Body="", File=None, Filename=""):
- text = makePart(Body, "quoted-printable")
- text["Content-Type"] = "text/plain; charset=iso8859-1"
- if File is not None:
- data = File.read()
- if data:
- attach = makePart(File.read(), "base64")
- ext = os.path.splitext(Filename)[1]
- ctype = mimetypes.guess_type(ext)[0] or "application/octet-stream"
- attach["Content-Type"] = ctype
- attach["Content-Disposition"] = 'attachment; filename="%s"' % Filename
- msg = Message(StringIO())
- msg.boundary = choose_boundary()
- msg["Content-Type"] = 'multipart/mixed; boundary="%s"' % msg.boundary
- msg.parts.extend([text, attach])
- else: msg = text
- else: msg = text
- msg["From"] = From
- msg["X-Mailer"] = "BoboMail.py/%s" % __version__
- msg["To"] = To
- if Cc: msg["Cc"] = Cc
- if Bcc: msg["Bcc"] = Bcc
- msg["Subject"] = Subject
- msg["Mime-Version"] = "1.0"
- addrs = replace("%s, %s, %s" % (To, Cc or "", Bcc or ""), ";", ",")
- ToList = map(strip, split(addrs, ","))
- while "" in ToList: ToList.remove("")
- return sendMessage(From, ToList, msg)
- def sendMessage(From, ToList, msg):
- errors = []
- s = SMTP(smtp_host)
- failed = s.sendmail(From, ToList, str(msg))
- s.quit()
- for email, (code, reason) in failed.items():
- errors.append(SentFailed(email, code, reason))
- return errors
- if __name__ == "__main__":
- print sendmail(
- "hs@cs.uni-ol.de", "henning@localhost", None, None, "Testmail",
- "From Hallo LeutenGru