Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import sys
- import os
- import smtplib
- import imaplib
- import email
- import base64
- import re
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- class Mailer(object):
- """
- Replies to emails on yandex
- """
- __answer_html = ""
- __answer_text = ""
- __imap_server = "imap.yandex.ru"
- __imap_port = 993
- __smtp_server = "smtp.yandex.ru"
- __smtp_port = 465
- __mail_user = ""
- __mail_password = ""
- __from_filter = ""
- __filter_subject = ""
- __my_name = ""
- __subject_text = "Reply"
- def load_answer(self, filename):
- """ Loads answer template from file"""
- f = open(filename, encoding="utf-8", mode="r")
- try:
- self.__answer_html = '\n'.join(f.readlines())
- except Exception as e:
- print(e)
- print("Answer data not found!\n")
- f.close()
- def set_answer_text(self, text_answer):
- """ Not really needed, in case html is not supported"""
- self.__answer_text = text_answer
- def get_unread_emails(self):
- """ Reads emails, fetches user data with regexps """
- conn = imaplib.IMAP4_SSL(self.__imap_server, self.__imap_port)
- result = []
- try:
- print("Connecting to server...")
- (retcode, capabilities) = conn.login(self.__mail_user, self.__mail_password)
- except:
- print("Connect to mail server failed")
- return
- if retcode != 'OK':
- print("Connect failed")
- return
- conn.select() # Select inbox or default namespace
- (retcode, messages) = conn.search(None, '(UNSEEN)', '(FROM "%s")' % self.__from_filter)
- if retcode == 'OK':
- i = 0
- letters = messages[0].split()
- print("%i new letters, processing" % len(letters))
- print(40 * '-')
- for num in letters:
- i += 1
- print('Processing : %i letter...' % i)
- typ, data = conn.fetch(num, '(UID BODY[TEXT])') #'(RFC822)'
- typ, hdrs = conn.fetch(num, '(RFC822)')
- message = email.message_from_bytes(hdrs[0][1])
- date = message['Date']
- for response_part in data:
- if isinstance(response_part, tuple):
- original = email.message_from_bytes(response_part[1])
- try:
- body = base64.b64decode(original.as_string()).decode("utf-8")
- except:
- body = original.as_string()
- body = body.replace('=\n', '').replace('\n', '')
- #print(body)
- first_name = re.search('First_name: (.*?)<', body).group(1)
- last_name = re.search('Last_name: (.*?)<br', body).group(1)
- user_email = re.search('email: (.*?)<', body).group(1)
- result_answ = self.parse_answer_body(date, body)
- result.append({
- "first_name" : first_name,
- "last_name" : last_name,
- "email" : user_email,
- "body_user" : result_answ
- })
- ret, msg = conn.store(num,'+FLAGS','\\Seen')
- if ret == 'OK':
- print(ret, '\t%i read successfully' % i, '\n', 30 * '-')
- conn.close()
- return result
- def send_answers(self, user_data):
- """ Sends answers by template"""
- mail = smtplib.SMTP_SSL(self.__smtp_server, self.__smtp_port)
- try:
- print("Connecting to server before sending...")
- mail.login(self.__mail_user, self.__mail_password)
- except:
- print("Connect to mail server failed")
- return
- print("Started processing answers", '\n', 30 * '-')
- for user in user_data:
- first_name = user["first_name"]
- last_name = user["last_name"]
- user_email = user["email"]
- body_user = user["body_user"]
- print(type(first_name))
- print("Processing ", first_name, " ", last_name)
- msg = MIMEMultipart('alternative')
- msg['Subject'] = self.__subject_text
- msg['From'] = self.__mail_user
- msg['To'] = user_email
- text = self.__answer_text.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%answerer%", self.__my_name)
- html = self.__answer_html.replace("%first_name%", first_name).replace("%last_name%", last_name).replace("%body_user%", body_user)
- part1 = MIMEText(text, 'plain')
- part2 = MIMEText(html, 'html')
- msg.attach(part1)
- msg.attach(part2)
- try:
- mail.sendmail(self.__mail_user, user_email, msg.as_string())
- msg['To'] = "sales@radexpro.ru"
- mail.sendmail(self.__mail_user, "sales@radexpro.ru", msg.as_string())
- except Exception as e:
- print(e)
- print("Done\n", 20 * '-')
- mail.quit()
- def get_answer_body(self):
- return self.__answer_html
- def set_from_filter(self, from_filter):
- self.__from_filter = from_filter
- def set_subject_filter(self, subject_filter):
- self.__subject_filter = subject_filter
- def set_mail_user(self, mail_user):
- self.__mail_user = mail_user
- def set_password(self, password):
- self.__mail_password = password
- def set_my_name(self, my_name):
- self.__my_name = my_name
- def set_subject(self, subject):
- self.__subject_text = subject
- if __name__ == '__main__':
- mailer = Mailer()
- mailer.load_answer(os.path.join(os.getcwd(), "answer_ru.html"))
- #mailer.load_answer("C:\\RADEXPRO\\Mailer\\yandex-mail-answerer\\answer_ru.html")
- # -*- coding: utf-8 -*-
- answer_text = u'Инструкции о том, как скачать и инициализировать пробную версию программы, а также все необходимые ссылки'
- mailer.set_answer_text(ololo)
- mailer.set_from_filter("site@radexpro.ru") #replace with yours
- mailer.set_my_name("Polina") #replace with yours
- mailer.set_mail_user("pb@radexpro.ru") #replace with yours
- mailer.set_subject("Request for free trial from RadExPro site") #replace with yours
- mailer.set_password("") #replace with yours
- mailer.set_subject_filter("Запрос пробной версии")
- # receiving
- #print(mailer.get_unread_emails())
- mailer.send_answers(mailer.get_unread_emails())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement