Subversion Repositories SmartDukaan

Rev

Rev 4909 | Rev 5194 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4795 mandeep.dh 1
from email.mime.text import MIMEText
2
from shop2020.clients.HelperClient import HelperClient
1425 varun.gupt 3
from shop2020.thriftpy.utils.ttypes import Mail
4909 amar.kumar 4
from shop2020.utils.daemon import Daemon
5
 
4795 mandeep.dh 6
import sched
7
import time
8
import smtplib
9
import sys
4909 amar.kumar 10
import optparse
1425 varun.gupt 11
 
12
 
4909 amar.kumar 13
class EmailSender(Daemon):
14
    def __init__(self, logfile='/var/log/utils/emailsender/emailsender.log', pidfile='/var/run/email-sender.pid'):
15
        Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)
3425 varun.gupt 16
        print 'EmailSender initiated at', time.time()
1425 varun.gupt 17
        self.email_schedular = sched.scheduler(time.time, time.sleep)
3425 varun.gupt 18
        self.time_to_sleep = 2
19
        self.authenticate()
20
 
21
    def authenticate(self):
3400 varun.gupt 22
        try:
3425 varun.gupt 23
            print "Attempting authentication at", time.time()
3987 mandeep.dh 24
            self.mailServer = smtplib.SMTP("smtp.sendgrid.net", 587)
3400 varun.gupt 25
 
3987 mandeep.dh 26
            self.sender = "shop2020mail"
27
            self.password = "shop2020"
3400 varun.gupt 28
            self.mailServer.ehlo()
29
            self.mailServer.starttls()
30
            self.mailServer.ehlo()
31
            self.mailServer.login(self.sender, self.password)
3425 varun.gupt 32
            print "Authentication successful", time.time()
3400 varun.gupt 33
 
34
        except smtplib.SMTPConnectError as e:
4795 mandeep.dh 35
            print 'Specified host did not respond correctly', e        
3400 varun.gupt 36
        except smtplib.SMTPHeloError as e:
37
            print 'The server did not reply properly to the HELO greeting.', e
38
        except smtplib.SMTPAuthenticationError as e:
39
            print 'The server did not accept the username/password combination.', e
40
        except smtplib.SMTPException as e:
41
            print e
4795 mandeep.dh 42
        except Exception as e:
43
            print sys.exc_info()[0]
44
            print e
3425 varun.gupt 45
 
1425 varun.gupt 46
    def sendMail(self, mail):
47
        if mail.sender:
48
            mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
49
 
1560 varun.gupt 50
        msg = MIMEText(mail.data, 'html')
1425 varun.gupt 51
 
1566 varun.gupt 52
        msg['To'] = mail.to
53
 
1425 varun.gupt 54
        if mail.sender:
55
            msg['From'] = mail.sender
56
        else:
57
            msg['From'] = "help@saholic.com"
58
        msg['Subject'] = mail.subject
59
 
3425 varun.gupt 60
        try:
61
            rs = self.mailServer.sendmail(self.password, [mail.to], msg.as_string())
62
 
63
        except smtplib.SMTPServerDisconnected as e:
64
            print 'Server Disconnected at', time.time()
65
            self.authenticate()
66
            rs = self.mailServer.sendmail(self.password, [mail.to], msg.as_string())
67
 
68
        print msg['To']
1425 varun.gupt 69
        # Should be mailServer.quit(), but that crashes...
70
        return rs
71
 
72
    def send(self):
73
        print "Despatch stared at ", time.time()
74
        helper_client = HelperClient().get_client()
75
 
3086 rajveer 76
        emails_to_be_dispatched = helper_client.getEmailsToBeSent()
1425 varun.gupt 77
        print len(emails_to_be_dispatched)
78
 
79
        for email in emails_to_be_dispatched:
80
            mail = Mail(email.emailTo, email.subject, email.body, None, None, None)
81
 
3977 varun.gupt 82
            try:
83
                send_result = self.sendMail(mail)
4796 mandeep.dh 84
            except Exception as e:
85
                print sys.exc_info()[0]
86
                print e
3977 varun.gupt 87
                print 'Error occurred sending emails. Will retry.'
4971 mandeep.dh 88
                continue
89
 
90
            if len(send_result) == 0:
91
                print "Sent at", time.time()
92
                helper_client.markEmailAsSent(email.id)
93
            else:
94
                print "Failed sending email. Id:", " Time:", time.time()
3977 varun.gupt 95
 
1425 varun.gupt 96
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
97
 
4909 amar.kumar 98
    def run(self):
1425 varun.gupt 99
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
100
        self.email_schedular.run()
101
 
4909 amar.kumar 102
if __name__ == "__main__":
103
    parser = optparse.OptionParser()
104
    parser.add_option("-l", "--logfile", dest="logfile",
105
                      type="string",
106
                      help="Log all output to LOG_FILE",
107
                      )
108
    parser.add_option("-i", "--pidfile", dest="pidfile",
109
                      type="string",
110
                      help="Write the PID to pidfile")
111
    (options, args) = parser.parse_args()
112
    daemon = EmailSender(options.logfile, options.pidfile)
113
    if len(args) == 0:
114
        daemon.run()
115
    elif len(args) == 1:
116
        if 'start' == args[0]:
117
            daemon.start()
118
        elif 'stop' == args[0]:
119
            daemon.stop()
120
        elif 'restart' == args[0]:
121
            daemon.restart()
122
        else:
123
            print "Unknown command"
124
            sys.exit(2)
125
        sys.exit(0)
126
    else:
127
        print "usage: %s start|stop|restart" % sys.argv[0]
128
        sys.exit(2)