⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mimemail.py

📁 python写的 发送mime邮件的模块
💻 PY
📖 第 1 页 / 共 2 页
字号:
                   'wrl'    : 'x-world/x-vrml'}

    def __get_img_type(self, data):
        """returns image type"""
        abc = data[:20].upper()
        if abc.find('GIF') != -1: ftype = 'gif'
        elif abc.find('JFIF') != -1 or abc.find('EXIF') != -1: ftype = 'jpeg'
        elif abc.find('PNG') != -1: ftype = 'png'
        elif abc.find('FWS') != -1 or abc.find('CWS') != -1: ftype = 'swf'
        else: ftype = ''
        return ftype

    def __get_inl_data(self, html, matches, css):
        """gets inline data from HTML document and returns updated HTML"""
        host = 'http://' + re.sub('/$', '', os.environ['HTTP_HOST'])
        ignore = re.compile('^(http|ftp|mailto|javascript)', re.IGNORECASE).search
        upperDir = re.compile(r'^\.\./').search
        repLastDir = re.compile(r'/[^/]+$').sub

        for m in matches:
            data = ''
            ext = ''
            fname = ''

            if not ignore(m[2]):
                inlName = m[2]
                ext = os.path.splitext(inlName)[1][1:]
                incl = 1

                for e in self.__exclude:
                    if e.find(ext) != -1:
                        incl = 0
                        break

                if incl:
                    if self.documentRoot:
                        doc_root = self.documentRoot

                        while upperDir(inlName):
                            inlName = inlName[3:]
                            doc_root = repLastDir('', doc_root)
                        fname = doc_root + '/' + inlName
                    else: fname = inlName

                    try:
                        fp = open(fname, 'rb')
                        try: data = fp.read()
                        finally: fp.close()
                    except IOError: pass

            if data:
                if not ext: ftype = self.__get_img_type(data)
                else: ftype = ext

                if css: html = html.replace(m[0], ' %s(cid:%s)' % (m[1], inlName))
                else: html = html.replace(m[0], ' %s="cid:%s"' % (m[1], inlName))

                if not self.__inline.has_key(ftype): self.__inline[ftype] = {}
                if not self.__inline[ftype].has_key(inlName):
                    self.__inline[ftype][inlName] = base64.encodestring(data)
            elif not ignore(m[2]):
                if css: html = html.replace(m[0], ' %s(%s/%s)' % (m[1], host, inlName))
                else: html = html.replace(m[0], ' %s="%s/%s"' % (m[1], host, inlName))
        return html

    def __check_body(self):
        """checks body of HTML mail for inline data"""
        matches = re.findall(r'( (src|background|href)="?([^" >]+)"?)', self.body, re.IGNORECASE)
        if matches: self.body = self.__get_inl_data(self.body, matches, 0)
        matches = re.findall(r'( (url)\(([^\)]+)\))', self.body, re.IGNORECASE)
        if matches: self.body = self.__get_inl_data(self.body, matches, 1)

        self.body = re.sub(r'<(table|tr|div)([^>]*)>\r?\n?', r'<\1\2>\n', self.body, re.IGNORECASE)
        self.body = re.sub(r'</(table|tr|td|style|script|div|p)>\r?\n?', r'</\1>\n', self.body, re.IGNORECASE)

    def __make_boundaries(self):
        """creates mail boundaries"""
        t = str(int(time.time()))
        self.__uid1 = 'Next_' + os.environ['SERVER_NAME'] + t + '1'
        self.__uid2 = 'Next_' + os.environ['SERVER_NAME'] + t + '2'
        self.__uid3 = 'Next_' + os.environ['SERVER_NAME'] + t + '3'

    def __build_header(self):
        """builds mail header"""
        self.__header = 'Return-Path: %s\n' % self.senderMail + \
                        'Subject: %s\n' % self.subject + \
                        'From: %s <%s>\n' % (self.senderName, self.senderMail) + \
                        'X-Sender: %s\n' % self.senderMail + \
                        'X-Mailer: MIMEmail (Python)\n' + \
                        'MIME-Version: 1.0\n'

        if self.replyTo: self.__header += 'Reply-To: %s\n' % self.replyTo
        if self.cc: self.__header += 'Cc: %s\n' % self.cc
        if self.bcc: self.__header += 'Bcc: %s\n' % self.bcc

        self.priority = self.priority.lower()
        if self.priority == 'high':
            priority = 1
            ms_priority = 'high'
        elif self.priority == 'low':
            priority = 5
            ms_priority = 'low'
        else:
            priority = 3
            ms_priority = 'normal'

        self.__header += 'X-Priority: %s\n' % priority + \
                         'X-MSMail-Priority: %s\n' % ms_priority

        if self.attachments:
            self.__header += 'Content-Type: multipart/mixed; boundary="%s"\n\n' % self.__uid1 + \
                             'This is a multi-part message in MIME format.\n\n' + \
                             '--%s\n' % self.__uid1

        if self.type == 'HTML':
            alternative = re.sub(r'<[a-z\/!][^>]*>', '', self.body)
            self.__header += 'Content-Type: multipart/alternative; boundary="%s"\n\n' % self.__uid3 + \
                             '--%s\n' % self.__uid3
            self.__header += 'Content-Type: text/plain; ' + \
                             'charset="%s"\n' % self.charSet + \
                             'Content-Transfer-Encoding: 8bit\n\n' + \
                             re.sub(r'(\s*\r?\n\s*){2}', r'\1\1', alternative) + '\n\n' + \
                             '--%s\n' % self.__uid3

            if self.__inline:
                self.__header += 'Content-Type: multipart/related; boundary="%s"\n\n' % self.__uid2 + \
                                 '--%s\n' % self.__uid2

        self.__header += 'Content-Type: text/%s; ' % ((self.type == 'HTML') and 'html' or 'plain') + \
                         'charset="%s"\n' % self.charSet + \
                         'Content-Transfer-Encoding: 8bit\n\n'

    def __build_footer(self):
        """builds mail footer"""
        atts = {}
        ftypes = {}
        self.__footer = ''

        for att in self.attachments:
            if att and att != 'none':
                try:
                    fp = open(att, 'rb')
                    filename = os.path.basename(att)
                    try:
                        file = fp.read()
                        ext = os.path.splitext(filename)[1][1:]
                        ftypes[filename] = self.__mimeTypes.has_key(ext) and self.__mimeTypes[ext] or self.__mimeTypes['bin']
                        atts[filename] = base64.encodestring(file)
                    finally: fp.close()
                except IOError: pass

        if self.__inline:
            for ftype, arr in self.__inline.items():
                for inlName, data in arr.items():
                    inlType = self.__mimeTypes.has_key(ftype) and self.__mimeTypes[ftype] or self.__mimeTypes['bin']
                    self.__footer += '--%s\n' % self.__uid2 + \
                                     'Content-Type: %s; name="%s"\n' % (inlType, inlName) + \
                                     'Content-ID: <%s>\n' % inlName + \
                                     'Content-Disposition: inline; filename="%s"\n' % inlName + \
                                     'Content-Transfer-Encoding: base64\n\n' + \
                                     '%s\n\n' % data
            self.__footer += '--%s--\n\n' % self.__uid2

        if self.type == 'HTML': self.__footer += '--%s--' % self.__uid3 + (atts and '\n\n' or '')

        if atts:
            for filename, file in atts.items():
                self.__footer += '--%s\n' % self.__uid1 + \
                                 'Content-Type: %s; name="%s"\n' % (ftypes[filename], filename) + \
                                 'Content-Disposition: attachment; filename="%s"\n' % filename + \
                                 'Content-Transfer-Encoding: base64\n\n' + \
                                 '%s\n\n' % file
            self.__footer += '--' + self.__uid1 + '--'

    def send(self, recipients):
        """sends MIME mail"""
        ok = 0

        if self.__created:
            self.__build_header()
            if hasattr(recipients, 'upper'): recipients = recipients.replace(' ', '').split(',')
            mimemail = 'To: ' + ', '.join(recipients) + '\n' + self.__header + self.body + '\n\n' + self.__footer

            if self.saveDir:
                file = self.saveDir + '/mail_' + str(self.__cnt + 1) + '.eml'
                try:
                    fp = open(file, 'w')
                    try:
                        fp.write(mimemail)
                        ok = 1
                    except: self.error = 'Could not write to "%s"' % file
                    fp.close()
                except IOError: self.error = 'Could not open "%s"' % file
            else:
                try:
                    server = smtplib.SMTP(self.smtpHost)
                    try:
                        server.sendmail(self.senderMail, recipients, mimemail)
                        ok = 1
                    except:
                        self.error = 'Error while sending e-mail'
                        if recipients.find(',') == -1: self.error += ' to "%s"' % recipients
                    server.quit()
                except: self.error = 'No connection to SMTP host "%s"' % self.smtpHost
            self.__cnt += 1
            self.subject = self.__subjectLine
            self.body = self.__bodyText
        else: self.error = 'MIME mail not created yet'
        return ok

    def create(self):
        """creates MIME mail"""
        self.__inline = {}

        if len(self.body) < 100:
            file = self.body

            try:
                fp = open(file, 'r')
                try: self.body = fp.read()
                finally: fp.close()
                self.documentRoot = os.path.dirname(file)
                self.documentRoot = self.documentRoot.replace('\\', '/')
            except IOError: pass

        if self.type == 'HTML': self.__check_body()
        self.__make_boundaries()
        self.__build_footer()
        self.__subjectLine = self.subject
        self.__bodyText = self.body
        self.__created = True

if __name__ == '__main__':
    print __doc__

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -