Subversion Repositories SmartDukaan

Rev

Rev 5299 | Rev 5864 | 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
5299 mandeep.dh 5
import optparse
4795 mandeep.dh 6
import sched
7
import smtplib
8
import sys
5299 mandeep.dh 9
import time
1425 varun.gupt 10
 
11
 
5299 mandeep.dh 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:
5299 mandeep.dh 23
            print "Attempting authentication at ", time.time()
24
            self.sendGridMailServer = smtplib.SMTP("smtp.sendgrid.net", 587)
25
            self.sendGridSender = "shop2020mail"
26
            self.sendGridPassword = "shop2020"
27
            self.sendGridMailServer.ehlo()
28
            self.sendGridMailServer.starttls()
29
            self.sendGridMailServer.ehlo()
30
            self.sendGridMailServer.login(self.sendGridSender, self.sendGridPassword)
31
 
32
            self.gmailServer = smtplib.SMTP("smtp.gmail.com", 587)
33
            self.gmailSender = "help@shop2020.in"
34
            self.gmailPassword = "5h0p2o2o"
35
            self.gmailServer.ehlo()
36
            self.gmailServer.starttls()
37
            self.gmailServer.ehlo()
38
            self.gmailServer.login(self.gmailSender, self.gmailPassword)            
3425 varun.gupt 39
            print "Authentication successful", time.time()
3400 varun.gupt 40
 
41
        except smtplib.SMTPConnectError as e:
4795 mandeep.dh 42
            print 'Specified host did not respond correctly', e        
3400 varun.gupt 43
        except smtplib.SMTPHeloError as e:
44
            print 'The server did not reply properly to the HELO greeting.', e
45
        except smtplib.SMTPAuthenticationError as e:
46
            print 'The server did not accept the username/password combination.', e
47
        except smtplib.SMTPException as e:
48
            print e
4795 mandeep.dh 49
        except Exception as e:
50
            print sys.exc_info()[0]
51
            print e
3425 varun.gupt 52
 
1425 varun.gupt 53
    def sendMail(self, mail):
54
        if mail.sender:
55
            mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
56
 
1560 varun.gupt 57
        msg = MIMEText(mail.data, 'html')
1425 varun.gupt 58
 
5194 anupam.sin 59
        msg['To'] = ';'.join(mail.to)
1566 varun.gupt 60
 
1425 varun.gupt 61
        if mail.sender:
62
            msg['From'] = mail.sender
63
        else:
64
            msg['From'] = "help@saholic.com"
65
        msg['Subject'] = mail.subject
66
 
3425 varun.gupt 67
        try:
5299 mandeep.dh 68
            self.setMailServerAndPassword(mail)
5194 anupam.sin 69
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 70
        except smtplib.SMTPServerDisconnected as e:
71
            print 'Server Disconnected at', time.time()
72
            self.authenticate()
5194 anupam.sin 73
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 74
 
75
        print msg['To']
1425 varun.gupt 76
        # Should be mailServer.quit(), but that crashes...
77
        return rs
78
 
5299 mandeep.dh 79
    def setMailServerAndPassword(self, mail):
5828 rajveer 80
        self.mailServer = self.sendGridMailServer
81
        self.password = self.sendGridPassword
82
 
83
#        self.mailServer = self.gmailServer
84
#        self.password = self.gmailPassword
85
#
86
#        for receiver in mail.to:
87
#            if not receiver.endswith('@saholic.com') and not receiver.endswith('@shop2020.in'):
88
#                self.mailServer = self.sendGridMailServer
89
#                self.password = self.sendGridPassword
90
#                break
5299 mandeep.dh 91
 
1425 varun.gupt 92
    def send(self):
93
        print "Despatch stared at ", time.time()
94
        helper_client = HelperClient().get_client()
95
 
3086 rajveer 96
        emails_to_be_dispatched = helper_client.getEmailsToBeSent()
1425 varun.gupt 97
        print len(emails_to_be_dispatched)
98
 
99
        for email in emails_to_be_dispatched:
5194 anupam.sin 100
            toList = []
101
            for to in email.emailTo.split(';') :
5197 anupam.sin 102
                if to.strip() :
103
                    toList.append(to.strip())
5194 anupam.sin 104
            mail = Mail( toList, email.subject, email.body, None, None, None)
1425 varun.gupt 105
 
3977 varun.gupt 106
            try:
107
                send_result = self.sendMail(mail)
4796 mandeep.dh 108
            except Exception as e:
109
                print sys.exc_info()[0]
110
                print e
3977 varun.gupt 111
                print 'Error occurred sending emails. Will retry.'
4971 mandeep.dh 112
                continue
113
 
114
            if len(send_result) == 0:
115
                print "Sent at", time.time()
116
                helper_client.markEmailAsSent(email.id)
117
            else:
118
                print "Failed sending email. Id:", " Time:", time.time()
3977 varun.gupt 119
 
1425 varun.gupt 120
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
121
 
4909 amar.kumar 122
    def run(self):
1425 varun.gupt 123
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
124
        self.email_schedular.run()
125
 
4909 amar.kumar 126
if __name__ == "__main__":
127
    parser = optparse.OptionParser()
128
    parser.add_option("-l", "--logfile", dest="logfile",
129
                      type="string",
130
                      help="Log all output to LOG_FILE",
131
                      )
132
    parser.add_option("-i", "--pidfile", dest="pidfile",
133
                      type="string",
134
                      help="Write the PID to pidfile")
135
    (options, args) = parser.parse_args()
136
    daemon = EmailSender(options.logfile, options.pidfile)
137
    if len(args) == 0:
138
        daemon.run()
139
    elif len(args) == 1:
140
        if 'start' == args[0]:
141
            daemon.start()
142
        elif 'stop' == args[0]:
143
            daemon.stop()
144
        elif 'restart' == args[0]:
145
            daemon.restart()
146
        else:
147
            print "Unknown command"
148
            sys.exit(2)
149
        sys.exit(0)
150
    else:
151
        print "usage: %s start|stop|restart" % sys.argv[0]
152
        sys.exit(2)