Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.38 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import string
  4. import sys
  5. import ConfigParser
  6. import socket
  7. import smtplib
  8. import email
  9. import imaplib
  10. import quopri
  11. import re
  12. import calendar
  13. import time
  14.  
  15.  
  16. def logthis(prefix,msg):
  17. print "[%s] %s" %(prefix,msg)
  18.  
  19. class Config:
  20. def __init__(self):
  21. self.config = ConfigParser.ConfigParser()
  22. self.config.read("file.conf")
  23. self.sections = self.config.sections
  24.  
  25. def get_atributes(self,list_name):
  26. try:
  27. self.list_name = list_name
  28. self.username = list_name
  29. self.domain = self.config.get(list_name,'domain')
  30. self.source = self.config.get(list_name,'source')
  31. self.max_size = int(self.config.get(list_name,'max_size'))
  32. self.subject = self.config.get(list_name,'subject')
  33. self.password = self.config.get(list_name,'password')
  34. self.imapserver = self.config.get(list_name,'imap_host')
  35. self.smtpserver = self.config.get(list_name,'smtp_host')
  36. return True
  37. except ConfigParser.NoOptionError,e:
  38. logthis(self.list_name,e)
  39. return False
  40.  
  41. class Baloo:
  42.  
  43. def __init__(self,list_name):
  44. self.cfg = Config()
  45. # Check config attributes
  46. if self.cfg.get_atributes(list_name) == True:
  47. # Check source users list
  48. if self.read_source() == True:
  49. self._connect()
  50.  
  51. def read_source(self):
  52. try:
  53. with open(self.cfg.source) as f:
  54. self.USER_DATABASE = f.readlines()
  55. # remove newline char
  56. self.USER_DATABASE = map(string.strip,self.USER_DATABASE)
  57. return True
  58. except IOError,e:
  59. logthis(self.cfg.list_name,e)
  60. return False
  61.  
  62. def _connect(self):
  63. try:
  64. # Log-in in imap using SSL
  65. self.conn = imaplib.IMAP4_SSL(self.cfg.imapserver)
  66. self.conn.login(self.cfg.username,self.cfg.password)
  67. # create mail boxes
  68. # print self.conn.list()
  69. current_month = calendar.month_abbr[time.localtime().tm_mon]
  70. current_year = str(time.localtime().tm_year)
  71. store_box = current_month + current_year
  72. if self.conn.select('OVERSIZE')[0] == 'NO': self.conn.create('OVERSIZE')
  73. if self.conn.select('INVALID')[0] == 'NO': self.conn.create('INVALID')
  74. if self.conn.select('CMD')[0] == 'NO': self.conn.create('CMD')
  75. if self.conn.select(store_box)[0] == 'NO': self.conn.create(store_box)
  76. # Select inbox and look for new messages
  77. if self.conn.select('INBOX')[0] != 'NO':
  78. return_code, data_range = self.conn.search(None,'ALL')
  79. self._retrieve(data_range)
  80. else:
  81. logthis(self.cfg.list_name,"inbox not found")
  82. except imaplib.IMAP4.error,e:
  83. logthis(self.cfg.list_name,e)
  84. except socket.gaierror,e:
  85. logthis(self.cfg.list_name,e)
  86.  
  87. def _retrieve(self,data_range):
  88. print "Processing %d messages" % (len(data_range))
  89. for msg_id in data_range[0].split():
  90. self.mm = MailMessage(msg_id,self.conn.fetch(msg_id,'(RFC822)'))
  91. self.check_server_msg()
  92. # remove all messages marked to be removed
  93. self.conn.expunge()
  94. self.conn.logout()
  95.  
  96. def check_server_msg(self):
  97. # Authorization based on True/False
  98. # Here should apply rules
  99. forward_flag = []
  100. forward_flag.append(self.is_allowed_user(self.mm.return_path))
  101. forward_flag.append(self.check_size())
  102.  
  103. if forward_flag[0] == True:
  104. if forward_flag[1] == True:
  105. print "* Sending message from",self.mm.mail_from
  106. self._send(self.mm.mail_subject,self.mm.mail_from)
  107. self.conn.copy(self.mm.id,self.month_box)
  108. self.conn.store(self.mm.id, '+FLAGS', '\\Deleted')
  109. else:
  110. print "Return a message, complaining about max_size"
  111. self.conn.copy(self.mm.id,'OVERSIZE')
  112. self.conn.store(self.mm.id, '+FLAGS', '\\Deleted')
  113. else:
  114. print "Do not send message from",self.mm.mail_from
  115. self.conn.copy(self.mm.id,'INVALID')
  116. self.conn.store(self.mm.id, '+FLAGS', '\\Deleted')
  117.  
  118. def check_size(self):
  119. maxsize = self.cfg.max_size + 1000000
  120. if int(self.mm.size) > maxsize:
  121. return False
  122. else:
  123. return True
  124.  
  125. def is_allowed_user(self,return_path):
  126. for user in self.USER_DATABASE:
  127. if return_path == '':
  128. return False
  129. if user.replace('\n','') == return_path:
  130. return True
  131. return False
  132.  
  133. def _send(self,mail_subject,mail_from):
  134. server = smtplib.SMTP(self.cfg.smtpserver,25)
  135. server.ehlo()
  136. server.starttls()
  137. server.ehlo()
  138. server.login(self.cfg.username,self.cfg.password)
  139.  
  140. # Get message and change headers
  141. msg = self.mm.msg
  142. msg.replace_header('Subject',self.cfg.subject+" "+mail_subject)
  143.  
  144. for user in self.USER_DATABASE:
  145. user = user.replace('\n','')
  146. #msg.replace_header('To',user)
  147. if user != '':
  148. print " - sending to",user
  149. server.sendmail(self.cfg.username,user,msg.as_string())
  150. server.quit()
  151.  
  152.  
  153. class MailMessage:
  154. def __init__(self,msg_id,result):
  155. self.id = msg_id
  156. rt_cod, self.mail_data = result
  157.  
  158. self._get_size()
  159. self._get_content()
  160. self._get_mail_object()
  161. self._get_headers()
  162.  
  163. def _get_size(self):
  164. self.size = re.findall('{[0-9]*}',self.mail_data[0][0])[0][1:-1]
  165.  
  166. def _get_content(self):
  167. self.msg_content = quopri.decodestring(self.mail_data[0][1])
  168.  
  169. def _get_mail_object(self):
  170. self.msg = email.message_from_string(self.msg_content)
  171.  
  172. def _get_headers(self):
  173. recv = ''
  174. for i in self.msg.items():
  175. if i[0] == 'Return-Path':
  176. return_path = i[1]
  177. self.return_path = return_path[1:-1]
  178. if i[0] == 'Subject':
  179. self.mail_subject = i[1]
  180. if i[0] == 'From':
  181. self.mail_from = i[1]
  182. if i[0] == 'Received':
  183. self.recv = recv + i[1] + "\n"
  184.  
  185. if __name__ == '__main__':
  186. config = Config()
  187. sections = config.sections()
  188.  
  189. for section in sections:
  190. Baloo(section)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement