Python模块学习——email

 

#!/usr/bin/python
#Sendmailpro.py
import re
import datetime

class PySendMail:
    def __init__(self,user='mailuser',userpass='mailpass',smtpserver='x.x.x.x',fro='mailuser <mailuser@mailuser.com>'):
        self.user = user
        self.userpass = userpass
        self.smtpserver = smtpserver
        self.fro = fro
   
    def sendmail(self,mailto='',mailsub='',attachtext='',textype='plain',dctype='application/octet-stream',filelist='',login=1,debug=0):
        import smtplib
        import mimetypes
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders
        from email.MIMEImage import MIMEImage

        addrlist1 = re.split('\s*[,|;]\s*',mailto)
        addrlist = []
        for addr in addrlist1:
            if  re.match('\s*\S+@\S+\.\S+',addr): addrlist.append(addr)
        msg = MIMEMultipart()
        msg['From'] = self.fro
        msg['To'] = COMMASPACE.join(addrlist)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = mailsub
        maintype = 'text'
        if textype == 'plain' or textype == 'html':
            txtsubtype = textype
        fpld =  MIMEBase (maintype, txtsubtype)
        fpld.set_payload(attachtext)
        Encoders.encode_base64(fpld)
        msg.attach(fpld)
           
        mailfilelist = []
        if filelist:    mailfilelist = re.split('\s*[,|;]\s*',filelist)
        for adfile in mailfilelist:           
            ctype, encoding = mimetypes.guess_type(adfile)
            if ctype is None or encoding is not None:
                ctype = dctype
            maintype, subtype = ctype.split('/', 1)
            try:
                        fsock=open(adfile,'rb')
                        fplp =  MIMEBase (maintype, subtype)
                        fplp.set_payload(fsock.read())
                        Encoders.encode_base64(fplp)
                        fsock.close
                        fplp.add_header('Content-Disposition', 'attachment',filename=re.split('/',adfile)[-1])
                        msg.attach(fplp)
            except IOError:
                        print 'cant open file: %s ' %adfile 
        smtp = smtplib.SMTP(self.smtpserver)
        if debug:    smtp.debuglevel = 5
        if login:    smtp.login(self.user,self.userpass)
        smtp.sendmail(self.fro, addrlist, msg.as_string())
        smtp.close()

在其他模块或文件中调用:

 

import datetime
from Sendmailpro import PySendMail
today = datetime.date.today().strftime("%A (%a) %d/%m/%Y") 
m=PySendMail('jack','password','smtp.gmail.com','jack <jack@gmail.com>')
m.sendmail('jack@gmail.com','GEGW DB Report of '+today,'GEGW','plain','application/octet-stream','/tmp/result.txt',1,0) 
posted @ 2011-01-20 14:48  Jack.gao  阅读(5277)  评论(1编辑  收藏  举报