Subversion Repositories SmartDukaan

Rev

Rev 4971 | Rev 5197 | 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
 
5194 anupam.sin 52
        msg['To'] = ';'.join(mail.to)
1566 varun.gupt 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:
5194 anupam.sin 61
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 62
 
63
        except smtplib.SMTPServerDisconnected as e:
64
            print 'Server Disconnected at', time.time()
65
            self.authenticate()
5194 anupam.sin 66
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 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:
5194 anupam.sin 80
            toList = []
81
            for to in email.emailTo.split(';') :
82
                toList.append(to.strip())
83
            mail = Mail( toList, email.subject, email.body, None, None, None)
1425 varun.gupt 84
 
3977 varun.gupt 85
            try:
86
                send_result = self.sendMail(mail)
4796 mandeep.dh 87
            except Exception as e:
88
                print sys.exc_info()[0]
89
                print e
3977 varun.gupt 90
                print 'Error occurred sending emails. Will retry.'
4971 mandeep.dh 91
                continue
92
 
93
            if len(send_result) == 0:
94
                print "Sent at", time.time()
95
                helper_client.markEmailAsSent(email.id)
96
            else:
97
                print "Failed sending email. Id:", " Time:", time.time()
3977 varun.gupt 98
 
1425 varun.gupt 99
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
100
 
4909 amar.kumar 101
    def run(self):
1425 varun.gupt 102
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
103
        self.email_schedular.run()
104
 
4909 amar.kumar 105
if __name__ == "__main__":
106
    parser = optparse.OptionParser()
107
    parser.add_option("-l", "--logfile", dest="logfile",
108
                      type="string",
109
                      help="Log all output to LOG_FILE",
110
                      )
111
    parser.add_option("-i", "--pidfile", dest="pidfile",
112
                      type="string",
113
                      help="Write the PID to pidfile")
114
    (options, args) = parser.parse_args()
115
    daemon = EmailSender(options.logfile, options.pidfile)
116
    if len(args) == 0:
117
        daemon.run()
118
    elif len(args) == 1:
119
        if 'start' == args[0]:
120
            daemon.start()
121
        elif 'stop' == args[0]:
122
            daemon.stop()
123
        elif 'restart' == args[0]:
124
            daemon.restart()
125
        else:
126
            print "Unknown command"
127
            sys.exit(2)
128
        sys.exit(0)
129
    else:
130
        print "usage: %s start|stop|restart" % sys.argv[0]
131
        sys.exit(2)