Advertisement
PolyAka

Untitled

Mar 10th, 2016
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.36 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import sys
  4. import os
  5. import smtplib
  6. import imaplib
  7. import email
  8. import base64
  9. import re
  10.  
  11. from email.mime.multipart import MIMEMultipart
  12. from email.mime.text import MIMEText
  13.  
  14. class Mailer(object):
  15.     """
  16.      Replies to emails on yandex
  17.   """
  18.    
  19.     __answer_html = ""
  20.     __answer_text = ""
  21.     __imap_server = "imap.yandex.ru"
  22.     __imap_port = 993
  23.     __smtp_server = "smtp.yandex.ru"
  24.     __smtp_port = 465
  25.     __mail_user = ""  
  26.     __mail_password = ""
  27.     __from_filter = ""
  28.     __filter_subject = ""
  29.  
  30.     __my_name = ""
  31.     __subject_text = "Reply"
  32.    
  33.     def load_answer(self, filename):
  34.         """ Loads answer template from file"""
  35.         f = open(filename, encoding="utf-8", mode="r")
  36.         try:
  37.             self.__answer_html = '\n'.join(f.readlines())
  38.         except Exception as e:
  39.             print(e)
  40.             print("Answer data not found!\n")
  41.         f.close()
  42.        
  43.     def set_answer_text(self, text_answer):
  44.         """ Not really needed, in case html is not supported"""
  45.         self.__answer_text = text_answer
  46.        
  47.     def get_unread_emails(self):
  48.         """ Reads emails, fetches user data with regexps """
  49.         conn = imaplib.IMAP4_SSL(self.__imap_server, self.__imap_port)
  50.         result = []
  51.  
  52.         try:
  53.             print("Connecting to server...")
  54.             (retcode, capabilities) = conn.login(self.__mail_user, self.__mail_password)
  55.         except:
  56.             print("Connect to mail server failed")
  57.             return
  58.            
  59.         if retcode != 'OK':
  60.             print("Connect failed")
  61.             return
  62.  
  63.         conn.select() # Select inbox or default namespace
  64.         (retcode, messages) = conn.search(None, '(UNSEEN)', '(FROM "%s")' % self.__from_filter)
  65.         if retcode == 'OK':
  66.             i = 0
  67.             letters = messages[0].split()
  68.             print("%i new letters, processing" % len(letters))
  69.             print(40 * '-')
  70.             for num in letters:
  71.                 i += 1
  72.                 print('Processing : %i letter...' % i)
  73.                
  74.                 typ, data = conn.fetch(num, '(UID BODY[TEXT])') #'(RFC822)'
  75.                 typ, hdrs = conn.fetch(num, '(RFC822)')
  76.                 message = email.message_from_bytes(hdrs[0][1])
  77.                 date = message['Date']
  78.                
  79.                 for response_part in data:
  80.                     if isinstance(response_part, tuple):
  81.                         original = email.message_from_bytes(response_part[1])
  82.                        
  83.                         try:
  84.                             body = base64.b64decode(original.as_string()).decode("utf-8")
  85.                         except:
  86.                             body = original.as_string()
  87.                            
  88.                         body = body.replace('=\n', '').replace('\n', '')
  89.                         #print(body)
  90.                        
  91.                         first_name = re.search('First_name: (.*?)<', body).group(1)
  92.                         last_name = re.search('Last_name: (.*?)<br', body).group(1)
  93.                         user_email = re.search('email: (.*?)<', body).group(1)
  94.                         result_answ = self.parse_answer_body(date, body)
  95.                        
  96.                         result.append({
  97.                             "first_name" : first_name,
  98.                             "last_name"  : last_name,
  99.                             "email"      : user_email,
  100.                             "body_user"  : result_answ
  101.                         })
  102.                        
  103.                         ret, msg = conn.store(num,'+FLAGS','\\Seen')
  104.                        
  105.                         if ret == 'OK':
  106.                             print(ret, '\t%i read successfully' % i, '\n', 30 * '-')
  107.                            
  108.         conn.close()
  109.         return result
  110.        
  111.     def send_answers(self, user_data):
  112.         """ Sends answers by template"""
  113.         mail = smtplib.SMTP_SSL(self.__smtp_server, self.__smtp_port)      
  114.  
  115.         try:
  116.             print("Connecting to server before sending...")        
  117.             mail.login(self.__mail_user, self.__mail_password)
  118.         except:
  119.             print("Connect to mail server failed")
  120.             return
  121.        
  122.         print("Started processing answers", '\n', 30 * '-')
  123.         for user in user_data:
  124.             first_name = user["first_name"]
  125.             last_name = user["last_name"]
  126.             user_email = user["email"]
  127.             body_user = user["body_user"]
  128.             print(type(first_name))
  129.             print("Processing ", first_name, " ", last_name)
  130.            
  131.             msg = MIMEMultipart('alternative')
  132.             msg['Subject'] = self.__subject_text
  133.             msg['From'] = self.__mail_user
  134.             msg['To'] = user_email
  135.            
  136.             text =  self.__answer_text.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%answerer%", self.__my_name)                                    
  137.             html =  self.__answer_html.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%body_user%", body_user)
  138.                                    
  139.             part1 = MIMEText(text, 'plain')
  140.             part2 = MIMEText(html, 'html')
  141.            
  142.             msg.attach(part1)
  143.             msg.attach(part2)        
  144.            
  145.             try:
  146.                 mail.sendmail(self.__mail_user, user_email, msg.as_string())
  147.                 msg['To'] = "sales@radexpro.ru"
  148.                 mail.sendmail(self.__mail_user, "sales@radexpro.ru", msg.as_string())
  149.             except Exception as e:
  150.                 print(e)
  151.                
  152.             print("Done\n", 20 * '-')
  153.                      
  154.         mail.quit()
  155.        
  156.     def get_answer_body(self):
  157.         return self.__answer_html
  158.        
  159.     def set_from_filter(self, from_filter):
  160.         self.__from_filter = from_filter
  161.        
  162.     def set_subject_filter(self, subject_filter):
  163.         self.__subject_filter = subject_filter        
  164.        
  165.     def set_mail_user(self, mail_user):
  166.         self.__mail_user = mail_user
  167.        
  168.     def set_password(self, password):
  169.         self.__mail_password = password
  170.        
  171.     def set_my_name(self, my_name):
  172.         self.__my_name = my_name
  173.        
  174.     def set_subject(self, subject):
  175.         self.__subject_text = subject
  176.      
  177.  
  178. if __name__ == '__main__':
  179.     mailer = Mailer()
  180.     mailer.load_answer(os.path.join(os.getcwd(), "answer_ru.html"))
  181.     #mailer.load_answer("C:\\RADEXPRO\\Mailer\\yandex-mail-answerer\\answer_ru.html")
  182. # -*- coding: utf-8 -*-
  183.     answer_text = u'Инструкции о том, как скачать и инициализировать пробную версию программы, а также все необходимые ссылки'
  184.     mailer.set_answer_text(ololo)
  185.     mailer.set_from_filter("site@radexpro.ru") #replace with yours
  186.     mailer.set_my_name("Polina")                #replace with yours
  187.     mailer.set_mail_user("pb@radexpro.ru")       #replace with yours
  188.     mailer.set_subject("Request for free trial from RadExPro site")                 #replace with yours
  189.     mailer.set_password("")            #replace with yours
  190.     mailer.set_subject_filter("Запрос пробной версии")
  191.     # receiving
  192.     #print(mailer.get_unread_emails())
  193.     mailer.send_answers(mailer.get_unread_emails())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement