Python script for sending mail, with message content and attachments, message content in string format, attachment as file. If you want to send all the files in a directory as attachments, please remove the comments.
The code is as follows:
#!/usr/bin/python#coding utf-8from email. Mimetext import mimetextfrom email. Mimemultipart import mimemultipartfrom email. Mimebase import mimebasefrom email import utils, encodersimport typesimport smtplibimport socketimport base64import mimetypesimport osclass syk_mail (Object ): def __init__ (Self,smtpserver,sender,password): self.smtpserver = smtpserver Self.password = password self.s = none count = sender.find (' @ ') if count > -1: self.postfix = sender[count:] self.sender = sender[0:count] else: self.postfix = ' self.sender = sender def sendmailattach (Self,receiver,subject,body,path): try: msgatt = Mimemultipart (_charset= ' gb2312 ') msgatt [' to '] =receiver msgatt[' from '] = self.sender + self.postfix msgatt[' Subject '] = subject msgatt[' Date '] = Utils.formatdate (localtime=1) msgatt[' Message-id '] = utils.make_msgid () #body = Base64.encodestring (body) msg = mimetext (body) msg.add_header (' Content-language ', ' ZH-CN ') msg.add_ Header (' content-transfer-encoding ', ' base64 ') msg.add_header (' Content-type ', ' text/html;charset = ' gb2312 ') mSg.add_header (' content-disposition ', ' inline ') msgatt.attach (msg) Msgatt.attach (self.attachment (path)) # For root,dirs,files in os.walk (PATH): # for filespath in files: # msgatt.attach (Self.attachment (Os.path.join (root,filespath)) if self.s == None: self.s = smtplib. SMTP (Self.smtpserver) &Nbsp; self.s.set_debuglevel (True) self.s.login (Self.sender+self.postfix, Self.password) self.s.sendmail (msgatt[' from '],msgatt[ ' To '].split (';'), msgatt.as_string ()) except (Socket.gaierror,socket.error,socket.herror, Smtplib. Smtpexception),e: self.err = STR (e) return False return True def Attachment (self,fileName): if os.path.exists (filename) == false: return fd = open (filename, ' RB ') mimetype, Mimeencoding = mimetypes.guess_type (filename) maintype,subtype = "", "" if mimeencoding or (Mimetype is none): mimetype = ' Application/octet-stream ' maintype,subtype = mimetype.split ('/', 1) Retval = mimebase (Maintype,subtype) retval.set_ Payload (Fd.read ()) encoders.encode_base64 (retval) Retval.add_header (' content-disposition ', ' attchment ', filename=filename) fd.close () return retval#end script
This article is from the "just out of the shell of the Birds" blog, please be sure to keep this source http://qhd2004.blog.51cto.com/629417/1826273
Python script for sending messages