Python script for sending messages

Source: Internet
Author: User
Tags base64

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.