Advertisement
PolyAka

Untitled

Mar 10th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.32 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.     __subject_filter = ""
  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 parse_answer_body(self, date, body):
  48.         body = body.replace(' ', '')[:-7]
  49.         body = body[6:]
  50.         date = "<br/><p> ***"+ date + "***</p>"
  51.         return date + body
  52.        
  53.     def get_unread_emails(self):
  54.         """ Reads emails, fetches user data with regexps """
  55.         conn = imaplib.IMAP4_SSL(self.__imap_server, self.__imap_port)
  56.         result = []
  57.        
  58.         try:
  59.             print("Connecting to server...")
  60.             (retcode, capabilities) = conn.login(self.__mail_user, self.__mail_password)
  61.         except:
  62.             print("Connect to mail server failed")
  63.             return
  64.            
  65.         if retcode != 'OK':
  66.             print("Connect failed")
  67.             return
  68.  
  69.         conn.select() # Select inbox or default namespace
  70.         (retcode, messages) = conn.search(None, '(UNSEEN)', '(FROM "%s")' % self.__from_filter, '(HEADER Subject "%s")' % self.__subject_filter)
  71.         if retcode == 'OK':
  72.             i = 0
  73.             letters = messages[0].split()
  74.             print("%i new letters, processing" % len(letters))
  75.             print(40 * '-')
  76.             for num in letters:
  77.                 i += 1
  78.                 print('Processing : %i letter...' % i)
  79.                
  80.                 typ, data = conn.fetch(num, '(UID BODY[TEXT])') #'(RFC822)'
  81.                 typ, hdrs = conn.fetch(num, '(RFC822)')
  82.                 message = email.message_from_bytes(hdrs[0][1])
  83.                 date = message['Date']
  84.                 for response_part in data:
  85.                     if isinstance(response_part, tuple):
  86.                         original = email.message_from_bytes(response_part[1])
  87.                         body = original.as_string().replace('=\n', '').replace('\n', '')
  88.                         #print(body)
  89.                         try:
  90.                             first_name = re.search('First_name: (.*?)<', body).group(1)
  91.                             last_name = re.search('Last_name: (.*?)<br', body).group(1)
  92.                             user_email = re.search('email: (.*?)<', body).group(1)
  93.                         except:
  94.                             a = 'test'
  95.                         result_answ = self.parse_answer_body(date, body)                          
  96.                         print(result_answ)
  97.                         result.append({
  98.                             "first_name" : first_name,
  99.                             "last_name"  : last_name,
  100.                             "email"      : user_email,
  101.                             "body_user"  : result_answ
  102.                         })
  103.                        
  104.                         ret, msg = conn.store(num,'+FLAGS','\\Seen')
  105.                        
  106.                         if ret == 'OK':
  107.                             print(ret, '\t%i read successfully' % i, '\n', 30 * '-')
  108.                            
  109.         conn.close()
  110.         return result
  111.        
  112.     def send_answers(self, user_data):
  113.         """ Sends answers by template"""
  114.         mail = smtplib.SMTP_SSL(self.__smtp_server, self.__smtp_port)      
  115.  
  116.         try:
  117.             print("Connecting to server before sending...")        
  118.             mail.login(self.__mail_user, self.__mail_password)
  119.         except:
  120.             print("Connect to mail server failed")
  121.             return
  122.        
  123.         print("Started processing answers", '\n', 30 * '-')
  124.         for user in user_data:
  125.             first_name = user["first_name"]
  126.             last_name = user["last_name"]
  127.             user_email = user["email"]
  128.             body_user = user["body_user"]
  129.             print(type(first_name))
  130.             print("Processing ", first_name, " ", last_name)
  131.            
  132.             msg = MIMEMultipart('alternative')
  133.             msg['Subject'] = self.__subject_text
  134.             msg['From'] = self.__mail_user
  135.             msg['To'] = user_email
  136.            
  137.             text =  self.__answer_text.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%answerer%", self.__my_name)
  138.             #print(body_user)
  139.             html =  self.__answer_html.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%body_user%", body_user)
  140.                                    
  141.             part1 = MIMEText(text, 'plain')
  142.             part2 = MIMEText(html, 'html')
  143.            
  144.             msg.attach(part1)
  145.             msg.attach(part2)        
  146.            
  147.             try:
  148.                 mail.sendmail(self.__mail_user, user_email, msg.as_string())
  149.                 msg['To'] = "sales@radexpro.ru"
  150.                 mail.sendmail(self.__mail_user, "sales@radexpro.ru", msg.as_string())
  151.             except Exception as e:
  152.                 print(e)
  153.                
  154.             print("Done\n", 20 * '-')
  155.                      
  156.         mail.quit()
  157.        
  158.        
  159.     def get_answer_body(self):
  160.         return self.__answer_html
  161.        
  162.     def set_from_filter(self, from_filter):
  163.         self.__from_filter = from_filter
  164.        
  165.     def set_subject_filter(self, subject_filter):
  166.         self.__subject_filter = subject_filter        
  167.        
  168.     def set_mail_user(self, mail_user):
  169.         self.__mail_user = mail_user
  170.        
  171.     def set_password(self, password):
  172.         self.__mail_password = password
  173.        
  174.     def set_my_name(self, my_name):
  175.         self.__my_name = my_name
  176.        
  177.     def set_subject(self, subject):
  178.         self.__subject_text = subject
  179.  
  180.        
  181.        
  182.     def sendEngEmails(self):
  183.         mailer = Mailer()
  184.         mailer.load_answer(os.path.join(os.getcwd(), "answer_en.html"))
  185.         mailer.set_answer_text("Thank you for your interest in our software. For the instructions how to download and initialize...")
  186.         mailer.set_from_filter("site@radexpro.com") #replace with yours
  187.         mailer.set_my_name("Polina Blinova")                #replace with yours
  188.         mailer.set_mail_user("pb@radexpro.ru")       #replace with yours
  189.         mailer.set_subject("Re:Request for free trial from RadExPro site")                 #replace with yours
  190.         mailer.set_password("QiwoeP09871")            #replace with yours
  191.         mailer.set_subject_filter("Request for free trial")
  192.     # receiving
  193.     #print(mailer.get_unread_emails())
  194.         mailer.send_answers(mailer.get_unread_emails())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement