文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>mailfile.py

mailfile.py

时间:2010-04-03  来源:digwtx

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ConfigParser
from os.path import exists, expanduser

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from base64 import b64encode
from os.path import abspath, basename
from hashlib import md5
from base64 import b64encode

from getopt import getopt
import mimetypes, email, smtplib
import sys

class ConfigFile:
    def __init__(self):
        home = expanduser('~')
        self.rcfile = "%s/.mailfilerc" % home
        self.loadConfigFile()
    def initConfigFile(self):
        c = '''[mail]
from=xxx@@xxx.com
to=xxx@@xxx.com

[smtp]
host=smtp.xxx.com
port=25
user=xxx
passwd=xxx
'''
        f = open(self.rcfile,'w')
        f.write(c)
        f.close()
    def loadConfigFile(self):
        if exists(self.rcfile):
            cf = ConfigParser.ConfigParser()
            cf.read(self.rcfile)
            self.host = cf.get("smtp", "host")
            self.port = cf.getint("smtp", "port")
            self.user = cf.get("smtp", "user")
            self.passwd = cf.get("smtp", "passwd")
            self.FROM = cf.get('mail','from')
            self.TO = cf.get('mail','to')
        else:
            self.initConfigFile()
            print ('please edit the config file %s' % self.rcfile)

def sendmail(host,port,user,passwd,data):
    msg = email.message_from_string(data)
    FROM = email.utils.parseaddr(msg.get("from"))[1]
    TO = email.utils.parseaddr(msg.get("to"))[1]
    h = email.Header.Header(msg.get('subject'))
    SUBJECT = email.Header.decode_header(h)[0][0]
    print (('Connecting SMTP server %s ...') % host)
    smtp = smtplib.SMTP()
    smtp.connect('%s:%d' %(host, port))
    smtp.login(user, passwd)
    print (('send mail %s to <%s> ...') % (SUBJECT.decode('utf-8'),TO))
    smtp.sendmail(FROM, TO, data)
    smtp.quit()
    print (('mail sended. ^_^'))

class mail:
    def __init__(self, FROM, TO, SUBJECT='', CHARSET='utf-8'):
        self.FROM = FROM
        self.TO = TO
        self.SUBJECT = SUBJECT
        self.CHARSET = CHARSET
        self.text = ''
        self.fileinfo = '\n\n----\n'
        self.files = []
        self.msg = MIMEMultipart()
        self.msg['From'] = self.FROM
        self.msg['To'] = self.TO
    def addtext(self, text=''):
        self.text += text
    def addfile(self, FILE):
        fileName = r"%s" % abspath(FILE)
        f2 = basename(fileName)
        ctype, encoding = mimetypes.guess_type(fileName)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        att = MIMEImage((lambda f: (f.read(), f.close())) \
                        (open(fileName, 'rb'))[0], \
                        _subtype = subtype)
        att.add_header('Content-Disposition', \
                       'attachment', \
                       filename = self.utf8_b64(f2))
        att.set_charset(self.CHARSET)
        self.files.append(att)
        if not self.SUBJECT:
            self.SUBJECT += f2
        self.fileinfo += '%s\t%s\n' % (self.md5sum(fileName),f2)
    def makemail(self):
        self.msg['Subject'] = self.utf8_b64(self.SUBJECT)
        txt = MIMEText(self.utf8(self.text + self.fileinfo), \
                'plain', self.CHARSET)
        self.msg.attach(txt)
        for x in self.files:
            self.msg.attach(x)
    def utf8(self, text):
        try:
            return text.decode('mbcs').encode('utf-8')
        except:
            return text
    def utf8_b64(self, text):
        """encode into base64."""
        data = self.utf8(text)
        return '=?utf-8?B?%s?=' % b64encode(data)
    def md5sum(self, FILE):
        """return a file's md5sum."""
        m = md5()
        file = open(FILE,'r')
        bytes = file.read(1024)
        while(bytes != b''):
            m.update(bytes)
            bytes = file.read(1024)
        file.close()
        md5value = m.hexdigest()
        return md5value

def main():
    doc = '''\nUsage: %s [options] [address]
options:
    -a <file> \t\t add file to email
    -s <subject> \t set the subject of email
    -h, --help \t\t just for help \n''' % sys.argv[0]
    cf = ConfigFile()
    FROM = cf.FROM
    TO = cf.TO
    FLAGS1 = 'a:s:h'
    FLAGS2 = ['help']
    try:
        opts,args = getopt(sys.argv[1:], FLAGS1, FLAGS2)
    except:
        sys.exit(1)
    atts = []
    if not args:
        mailto = TO
    else:
        mailto = args[0]
    subject = ''
    for x, a in opts:
        if x in ('-a'):
            atts.append(a)
        elif x in ('-s'):
            subject = a
        elif x in ('-h','--help'):
            print doc
            return
    mymail = mail(FROM, mailto, subject)
    for file in atts:
        mymail.addfile(file)
    mymail.makemail()
    data = mymail.msg.as_string()
    #print data
    sendmail(cf.host, cf.port, cf.user, cf.passwd, data)

if __name__ == '__main__' :
    main()


相关阅读 更多 +
排行榜 更多 +
扑击萌兽大逃亡手游下载

扑击萌兽大逃亡手游下载

休闲益智 下载
gate交易平台app免费版

gate交易平台app免费版

金融理财 下载
Uniswap中文版app安卓版

Uniswap中文版app安卓版

金融理财 下载