def get_content(msg, ret): if msg.is_multipart(): ilen = len(msg.get_payload()) for i in range(0, ilen): subpart = msg.get_payload(i) get_content(subpart, ret) else: if not msg.get_param("name"): subtype = msg.get_content_subtype() #print msg.get("content-type") #print subtype chars = msg.get_content_charset() if chars: chars = chars.strip().lower() if chars == 'gb2312': chars = 'gbk' ret['charset'] = chars cnt = msg.get_payload(decode=True) try: cnt = unicode(cnt, ret['charset'], 'ignore') except Exception, e: logerr('charset convert error:', e) if subtype == 'plain': ret['plain'] = ret['plain'] + '\r\n' + cnt elif subtype == 'html': ret['html'] = cnt else:
def mails(self): name = self.mailuser['name'] count = 0 mailinfos = [] for item in self.uidls: i, k = item loginfo('uidl:', i, k) trycount = 0 while True: try: data = self.pop3.retr(i) except Exception, e: logerr(e) trycount += 1 if trycount == 3: break continue trycount = 0 break if trycount == 3: continue filedata = '\n'.join(data[1]) hashdir = '%02d' % (hash(k) % self.hashdir_count) filename = os.path.join(self.time_path, hashdir, '%d.' % (int(time.time())) + k + '.eml') loginfo('file:', filename, 'size:', len(filedata)) try: ret = mailparse.decode_mail_string(filedata) except Exception, e: traceback.print_exc(file=logfile.logobj.log) continue
def display_mailbox(self, name): loginfo('display name:', name) try: newobj = self.mailboxs[name] except Exception, e: logerr('mailbox error:', e) return False
def remove_file(self, filename): item = self.list.FindItem(-1, filename) if not item: logerr('not found:', filename) return data = self.list.GetItemData(item) if data: self.data.remove(data) self.list.DeleteItem(item)
def OnMailForward(self, event): data = self.tree.last_item_data() if not data: return user = data['user'] panel = data['panel'] try: info = panel.get_item_content() except Exception, e: logerr('get_item_content error:', str(e))
def OnActivate(self, evt): #loginfo('event:', evt) loginfo('OnActivate: %s' % self.tree.GetItemText(evt.GetItem())) self.lastitem = evt.GetItem() row = self.tree.GetItemData(evt.GetItem()).GetData() #loginfo('active row:', row) if not row: logerr('not found row.') return if not row.has_key('id'): loginfo('is category.') return #mid, name, mbox = s mid = row['id'] name = row['user'] mbox = row['box'] info = mailparse.decode_mail(row['filepath']) htmldata = info['html'] plaindata = info['plain'] #if htmldata: # self.parent.listcnt.set_text(htmldata) #elif plaindata: # self.parent.listcnt.set_text(plaindata.replace('\r\n', '<br>').replace('\n', '<br>')) self.parent.listcnt.set_text_auto(htmldata, plaindata) attachctl = self.parent.attachctl attachctl.clear() #row['attach'] = simplejson.loads(row['attach']) for item in row['attach']: filename = os.path.join(config.cf.datadir, name, row['mailbox'], row['filename'].strip(os.sep)) homename = os.path.join(config.cf.datadir, name) attachdata = {'file':filename, 'home':homename, 'attach':item[0]} loginfo('attachdata:', attachdata) attachctl.add_file(item[0], attachdata) if row['status'] == 'noread': #row['status'] = 'read' item = evt.GetItem() itemdata = self.tree.GetItemData(item).GetData() #loginfo('noread itemdata:', itemdata) self.draw_category_text(item, 'read') self.tree.SetItemBold(item, False) sql = "update mailinfo set status='read' where id=" + str(itemdata['id']) loginfo('read:', sql) db = dbope.openuser(config.cf, name) db.execute(sql) db.close() self.SetFocus()
def OnMailAttach(self, event): data = self.tree.last_item_data() if not data: wx.MessageBox(u"作为附件发送邮件失败!无法获取到当前邮件箱。", u"再次发送邮件") return user = data['user'] panel = data['panel'] try: info = panel.get_item_content() except Exception, e: logerr('get_item_content error:', str(e))
def connect(self, host='localhost', port = 0): if not port and (host.find(':') == host.rfind(':')): i = host.rfind(':') if i >= 0: host, port = host[:i], host[i+1:] try: port = int(port) except ValueError: raise socket.error, "nonnumeric port" if not port: port = SMTP_PORT if self.debuglevel > 0: logerr('connect:', (host, port)) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: logerr('connect:', sa) self.sock.settimeout(30) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: logerr('connect fail:', msg) if self.sock: self.sock.close() self.sock = None continue break
def parsedate(s): if not s: return '%d-%02d-%02d %02d:%02d:%02d' % time.localtime()[:6] s = s.strip() pos = s.find(',') if pos > 0: s = s[pos+1:].strip() ns = s.split() if s[0] in 'JFMAMJJASOND': ns = ns[1:] loginfo('ns:', ns) try: if len(ns) < 4: if ns[0].count('-') == 2: ts = ns[0].split('-') return '%s-%02d-%02d %s'% (ts[0], int(ts[1]), int(ts[2]), ns[1]) return '%d-%02d-%02d %02d:%02d:%02d' % time.localtime()[:6] if ns[3].count(':') == 1: ns[3] = ns[3] + ':00' return '%s-%02d-%s %s' % (ns[2], month[ns[1]], ns[0], ns[3]) except ValueError, e: logwarn('date string:', s) logerr(traceback.format_exc())
def mail(self): if self.uidl_pos >= len(self.uidls): return None name = self.mailuser['name'] count = 0 item = self.uidls[self.uidl_pos] self.uidl_pos += 1 i, k = item loginfo('uidl:', i, k) trycount = 0 while True: try: data = self.pop3.retr(i) except Exception, e: logerr(e) trycount += 1 if trycount == 3: raise ValueError, 'pop3 retr error:' + str(i) continue trycount = 0 break
def OnTimer(self, event): ''' 定时任务 ''' #print 'time now', time.ctime() for i in range(0,5): try: item = config.uiq.get(0) except: break else: loginfo('timer get uiq: ', item) name = item['name'] task = item['task'] boxpanel = self.mailboxs['/%s/' % (name) + u'收件箱'] if task == 'updatebox': usercf = config.cf.users[name] dbpath = os.path.join(config.cf.datadir, name, 'mailinfo.db') conn = dbope.DBOpe(dbpath, 'w') try: count = conn.query('select count(*) as count from mailinfo')[0]['count'] ret = conn.query("select id,filename,subject,fromuser,mailfrom,mailto,size,ctime,datetime(date,'unixepoch') as date,attach,mailbox,status from mailinfo where status='new' and mailbox='recv'") if ret: for info in ret: loginfo('get mail:', info['filename']) info['status'] = 'noread' self.load_db_info(name, info) conn.execute("update mailinfo set status='noread' where id=" + str(info['id'])) finally: conn.close() self.statusbar.SetStatusText(u'最后收信时间: %d-%02d-%02d %02d:%02d:%02d' % time.localtime()[:6], 1) elif task == 'newmail': filename = item['filename'] usercf = config.cf.users[name] dbpath = os.path.join(config.cf.datadir, name, 'mailinfo.db') conn = dbope.DBOpe(dbpath, 'w') try: ret = conn.query("select id,filename,subject,fromuser,mailfrom,mailto,size,ctime,datetime(date,'unixepoch') as date,attach,mailbox,status from mailinfo where filename='%s'" % (filename)) if ret: for info in ret: loginfo('get mail:', info['filename']) info['status'] = 'noread' self.load_db_info(name, info) conn.execute("update mailinfo set status='noread' where id=" + str(info['id'])) finally: conn.close() self.statusbar.SetStatusText(u'最后收信时间: %d-%02d-%02d %02d:%02d:%02d' % time.localtime()[:6], 1) s = u'%s 收信 %d/%d' % (name, item['count'], item['allcount']) self.statusbar.SetStatusText(s, 0) elif task == 'alert': wx.MessageBox(u'发送返回信息:' + item['message'], u'邮件信息!', wx.OK|wx.ICON_INFORMATION) if item['runtask'] == 'sendmail' and item['return']: boxpanel = self.mailboxs['/%s/' % (name) + u'发件箱'] dbpath = os.path.join(config.cf.datadir, name, 'mailinfo.db') conn = dbope.DBOpe(dbpath) try: ret = conn.query("select id,filename,subject,mailfrom,mailto,size,ctime,datetime(date,'unixepoch') as date,attach,mailbox,status from mailinfo where filename='%s'" % (item['filename'])) finally: conn.close() if ret: info = ret[0] loginfo('get mail:', info['filename']) att = 0 loginfo('attach:', info['attach']) if len(info['attach']) > 0: att = 1 info['user'] = name info['item'] = item['item'] info['box'] = '/%s/%s' % (name, info['mailbox']) info['filepath'] = os.path.join(config.cf.datadir, name, info['mailbox'], info['filename'].lstrip(os.sep)) loginfo('info:', info) boxpanel.change_box(info, 'sendover') elif task == 'status': pass else: logerr('uiq return error:', item)
def change_last_box(self, newbox='trash'): try: info = self.get_item_data() except Exception, e: logerr('get_item_content error:', str(e)) return