Subversion Repositories SmartDukaan

Rev

Rev 7546 | Rev 8020 | 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
6906 rajveer 3
from shop2020.clients.TransactionClient import TransactionClient
1425 varun.gupt 4
from shop2020.thriftpy.utils.ttypes import Mail
4909 amar.kumar 5
from shop2020.utils.daemon import Daemon
5299 mandeep.dh 6
import optparse
4795 mandeep.dh 7
import sched
8
import smtplib
9
import sys
5299 mandeep.dh 10
import time
6906 rajveer 11
import os
12
from email.MIMEMultipart import MIMEMultipart
13
from email.MIMEBase import MIMEBase
14
from email.MIMEText import MIMEText
15
from email import Encoders
1425 varun.gupt 16
 
17
 
5299 mandeep.dh 18
 
4909 amar.kumar 19
class EmailSender(Daemon):
20
    def __init__(self, logfile='/var/log/utils/emailsender/emailsender.log', pidfile='/var/run/email-sender.pid'):
21
        Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)
3425 varun.gupt 22
        print 'EmailSender initiated at', time.time()
1425 varun.gupt 23
        self.email_schedular = sched.scheduler(time.time, time.sleep)
3425 varun.gupt 24
        self.time_to_sleep = 2
25
        self.authenticate()
26
 
27
    def authenticate(self):
3400 varun.gupt 28
        try:
5299 mandeep.dh 29
            print "Attempting authentication at ", time.time()
30
            self.sendGridMailServer = smtplib.SMTP("smtp.sendgrid.net", 587)
6016 rajveer 31
            self.sendGridSender = "euser"
5299 mandeep.dh 32
            self.sendGridPassword = "shop2020"
33
            self.sendGridMailServer.ehlo()
34
            self.sendGridMailServer.starttls()
35
            self.sendGridMailServer.ehlo()
36
            self.sendGridMailServer.login(self.sendGridSender, self.sendGridPassword)
37
 
38
            self.gmailServer = smtplib.SMTP("smtp.gmail.com", 587)
39
            self.gmailSender = "help@shop2020.in"
40
            self.gmailPassword = "5h0p2o2o"
41
            self.gmailServer.ehlo()
42
            self.gmailServer.starttls()
43
            self.gmailServer.ehlo()
44
            self.gmailServer.login(self.gmailSender, self.gmailPassword)            
3425 varun.gupt 45
            print "Authentication successful", time.time()
3400 varun.gupt 46
 
47
        except smtplib.SMTPConnectError as e:
4795 mandeep.dh 48
            print 'Specified host did not respond correctly', e        
3400 varun.gupt 49
        except smtplib.SMTPHeloError as e:
50
            print 'The server did not reply properly to the HELO greeting.', e
51
        except smtplib.SMTPAuthenticationError as e:
52
            print 'The server did not accept the username/password combination.', e
53
        except smtplib.SMTPException as e:
54
            print e
4795 mandeep.dh 55
        except Exception as e:
56
            print sys.exc_info()[0]
57
            print e
3425 varun.gupt 58
 
6906 rajveer 59
    def get_attachment_part(self, document, filename):
60
        part = MIMEBase('application', 'octet-stream')
61
        part.set_payload(document)
62
        Encoders.encode_base64(part)
6947 rajveer 63
        part.add_header('Content-Disposition', 'attachment; filename=%s' % filename + "-insurance-policy.pdf")
6906 rajveer 64
        return part
65
 
1425 varun.gupt 66
    def sendMail(self, mail):
5864 rajveer 67
        msg = MIMEMultipart()
68
 
69
        msg['From'] = "help@saholic.com"
70
        msg['To'] = ', '.join(mail.emailTo)
71
        msg['Cc'] = ', '.join(mail.cc)
72
        #msg['Bcc'] = ', '.join(mail.bcc)
73
        msg['Subject'] = mail.subject
1425 varun.gupt 74
 
5864 rajveer 75
        html_msg = MIMEText(mail.body, 'html')
76
        msg.attach(html_msg)
6906 rajveer 77
 
78
        if mail.emailType == "DeliverySuccess":
79
            tclient = TransactionClient().get_client()
80
            document = tclient.getDocument(1, int(mail.source))
7040 amar.kumar 81
            if document != bin(0):
6906 rajveer 82
                msg.attach(self.get_attachment_part(document, mail.source))
83
 
3425 varun.gupt 84
        try:
5299 mandeep.dh 85
            self.setMailServerAndPassword(mail)
7550 anupam.sin 86
            rs = self.mailServer.sendmail(self.password, mail.emailTo + mail.cc + mail.bcc + ['backup@saholic.com'], msg.as_string())
3425 varun.gupt 87
        except smtplib.SMTPServerDisconnected as e:
88
            print 'Server Disconnected at', time.time()
89
            self.authenticate()
5194 anupam.sin 90
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 91
 
92
        print msg['To']
1425 varun.gupt 93
        # Should be mailServer.quit(), but that crashes...
94
        return rs
95
 
5299 mandeep.dh 96
    def setMailServerAndPassword(self, mail):
5828 rajveer 97
        self.mailServer = self.sendGridMailServer
98
        self.password = self.sendGridPassword
99
 
100
#        self.mailServer = self.gmailServer
101
#        self.password = self.gmailPassword
102
#
103
#        for receiver in mail.to:
104
#            if not receiver.endswith('@saholic.com') and not receiver.endswith('@shop2020.in'):
105
#                self.mailServer = self.sendGridMailServer
106
#                self.password = self.sendGridPassword
107
#                break
5299 mandeep.dh 108
 
1425 varun.gupt 109
    def send(self):
110
        print "Despatch stared at ", time.time()
111
        helper_client = HelperClient().get_client()
112
 
3086 rajveer 113
        emails_to_be_dispatched = helper_client.getEmailsToBeSent()
1425 varun.gupt 114
        print len(emails_to_be_dispatched)
115
 
116
        for email in emails_to_be_dispatched:
3977 varun.gupt 117
            try:
5864 rajveer 118
                send_result = self.sendMail(email)
4796 mandeep.dh 119
            except Exception as e:
120
                print sys.exc_info()[0]
121
                print e
3977 varun.gupt 122
                print 'Error occurred sending emails. Will retry.'
4971 mandeep.dh 123
                continue
124
 
125
            if len(send_result) == 0:
126
                print "Sent at", time.time()
127
                helper_client.markEmailAsSent(email.id)
128
            else:
129
                print "Failed sending email. Id:", " Time:", time.time()
3977 varun.gupt 130
 
1425 varun.gupt 131
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
132
 
4909 amar.kumar 133
    def run(self):
1425 varun.gupt 134
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
135
        self.email_schedular.run()
136
 
4909 amar.kumar 137
if __name__ == "__main__":
138
    parser = optparse.OptionParser()
139
    parser.add_option("-l", "--logfile", dest="logfile",
140
                      type="string",
141
                      help="Log all output to LOG_FILE",
142
                      )
143
    parser.add_option("-i", "--pidfile", dest="pidfile",
144
                      type="string",
145
                      help="Write the PID to pidfile")
146
    (options, args) = parser.parse_args()
147
    daemon = EmailSender(options.logfile, options.pidfile)
148
    if len(args) == 0:
149
        daemon.run()
150
    elif len(args) == 1:
151
        if 'start' == args[0]:
152
            daemon.start()
153
        elif 'stop' == args[0]:
154
            daemon.stop()
155
        elif 'restart' == args[0]:
156
            daemon.restart()
157
        else:
158
            print "Unknown command"
159
            sys.exit(2)
160
        sys.exit(0)
161
    else:
162
        print "usage: %s start|stop|restart" % sys.argv[0]
163
        sys.exit(2)