Rev 4909 | Rev 5197 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
from email.mime.text import MIMETextfrom shop2020.clients.HelperClient import HelperClientfrom shop2020.thriftpy.utils.ttypes import Mailfrom shop2020.utils.daemon import Daemonimport schedimport timeimport smtplibimport sysimport optparseclass EmailSender(Daemon):def __init__(self, logfile='/var/log/utils/emailsender/emailsender.log', pidfile='/var/run/email-sender.pid'):Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)print 'EmailSender initiated at', time.time()self.email_schedular = sched.scheduler(time.time, time.sleep)self.time_to_sleep = 2self.authenticate()def authenticate(self):try:print "Attempting authentication at", time.time()self.mailServer = smtplib.SMTP("smtp.sendgrid.net", 587)self.sender = "shop2020mail"self.password = "shop2020"self.mailServer.ehlo()self.mailServer.starttls()self.mailServer.ehlo()self.mailServer.login(self.sender, self.password)print "Authentication successful", time.time()except smtplib.SMTPConnectError as e:print 'Specified host did not respond correctly', eexcept smtplib.SMTPHeloError as e:print 'The server did not reply properly to the HELO greeting.', eexcept smtplib.SMTPAuthenticationError as e:print 'The server did not accept the username/password combination.', eexcept smtplib.SMTPException as e:print eexcept Exception as e:print sys.exc_info()[0]print edef sendMail(self, mail):if mail.sender:mail.data = "This mail is sent by " + mail.sender + "\n" + mail.datamsg = MIMEText(mail.data, 'html')msg['To'] = mail.toif mail.sender:msg['From'] = mail.senderelse:msg['From'] = "help@saholic.com"msg['Subject'] = mail.subjecttry:rs = self.mailServer.sendmail(self.password, [mail.to], msg.as_string())except smtplib.SMTPServerDisconnected as e:print 'Server Disconnected at', time.time()self.authenticate()rs = self.mailServer.sendmail(self.password, [mail.to], msg.as_string())print msg['To']# Should be mailServer.quit(), but that crashes...return rsdef send(self):print "Despatch stared at ", time.time()helper_client = HelperClient().get_client()emails_to_be_dispatched = helper_client.getEmailsToBeSent()print len(emails_to_be_dispatched)for email in emails_to_be_dispatched:mail = Mail(email.emailTo, email.subject, email.body, None, None, None)try:send_result = self.sendMail(mail)except Exception as e:print sys.exc_info()[0]print eprint 'Error occurred sending emails. Will retry.'continueif len(send_result) == 0:print "Sent at", time.time()helper_client.markEmailAsSent(email.id)else:print "Failed sending email. Id:", " Time:", time.time()self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())def run(self):self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())self.email_schedular.run()if __name__ == "__main__":parser = optparse.OptionParser()parser.add_option("-l", "--logfile", dest="logfile",type="string",help="Log all output to LOG_FILE",)parser.add_option("-i", "--pidfile", dest="pidfile",type="string",help="Write the PID to pidfile")(options, args) = parser.parse_args()daemon = EmailSender(options.logfile, options.pidfile)if len(args) == 0:daemon.run()elif len(args) == 1:if 'start' == args[0]:daemon.start()elif 'stop' == args[0]:daemon.stop()elif 'restart' == args[0]:daemon.restart()else:print "Unknown command"sys.exit(2)sys.exit(0)else:print "usage: %s start|stop|restart" % sys.argv[0]sys.exit(2)