Subversion Repositories SmartDukaan

Rev

Rev 15416 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
15385 manish.sha 1
from email import encoders
2
from email.mime.audio import MIMEAudio
3
from email.mime.base import MIMEBase
4
from email.mime.image import MIMEImage
5
from email.mime.multipart import MIMEMultipart
6
from email.mime.text import MIMEText
7
import mimetypes
8
import os
9
import re
10
import smtplib
11
import csv
12
import MySQLdb
13
from dtr.storage import DataService
14
from dtr.storage.DataService import Users
15
from elixir import *
16
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
17
from sqlalchemy.sql import func
18
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
19
    between
20
import datetime
21
from datetime import date,timedelta
22
 
23
 
24
class Email:
25
    """
26
    This class handles the creation and sending of email messages
27
    via SMTP.  This class also handles attachments and can send
28
    HTML messages.  The code comes from various places around
29
    the net and from my own brain.
30
    """
31
    def __init__(self, smtpServer):
32
        """
33
        Create a new empty email message object.
34
 
35
        @param smtpServer: The address of the SMTP server
36
        @type smtpServer: String
37
        """
38
        self._textBody = None
39
        self._htmlBody = None
40
        self._subject = ""
41
        self._smtpServer = smtpServer
42
        self._reEmail = re.compile("^([\\w \\._]+\\<[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\>|[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$")
43
        self.clearRecipients()
44
        self.clearAttachments()
45
 
46
    def send(self):
47
        """
48
        Send the email message represented by this object.
49
        """
50
        # Validate message
51
        if self._textBody is None and self._htmlBody is None:
52
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
53
        if len(self._to) == 0:
54
            raise Exception("Must specify at least one recipient")
55
 
56
        # Create the message part
57
        if self._textBody is not None and self._htmlBody is None:
58
            msg = MIMEText(self._textBody, "plain")
59
        elif self._textBody is None and self._htmlBody is not None:
60
            msg = MIMEText(self._htmlBody, "html")
61
        else:
62
            msg = MIMEMultipart("alternative")
63
            msg.attach(MIMEText(self._textBody, "plain"))
64
            msg.attach(MIMEText(self._htmlBody, "html"))
65
        # Add attachments, if any
66
        if len(self._attach) != 0:
67
            tmpmsg = msg
68
            msg = MIMEMultipart()
69
            msg.attach(tmpmsg)
70
        for fname,attachname in self._attach:
71
            if not os.path.exists(fname):
72
                print "File '%s' does not exist.  Not attaching to email." % fname
73
                continue
74
            if not os.path.isfile(fname):
75
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
76
                continue
77
            # Guess at encoding type
78
            ctype, encoding = mimetypes.guess_type(fname)
79
            if ctype is None or encoding is not None:
80
                # No guess could be made so use a binary type.
81
                ctype = 'application/octet-stream'
82
            maintype, subtype = ctype.split('/', 1)
83
            if maintype == 'text':
84
                fp = open(fname)
85
                attach = MIMEText(fp.read(), _subtype=subtype)
86
                fp.close()
87
            elif maintype == 'image':
88
                fp = open(fname, 'rb')
89
                attach = MIMEImage(fp.read(), _subtype=subtype)
90
                fp.close()
91
            elif maintype == 'audio':
92
                fp = open(fname, 'rb')
93
                attach = MIMEAudio(fp.read(), _subtype=subtype)
94
                fp.close()
95
            else:
96
                fp = open(fname, 'rb')
97
                attach = MIMEBase(maintype, subtype)
98
                attach.set_payload(fp.read())
99
                fp.close()
100
                # Encode the payload using Base64
101
                encoders.encode_base64(attach)
102
            # Set the filename parameter
103
            if attachname is None:
104
                filename = os.path.basename(fname)
105
            else:
106
                filename = attachname
107
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
108
            msg.attach(attach)
109
        # Some header stuff
110
        msg['Subject'] = self._subject
111
        msg['From'] = self._from
112
        msg['To'] = ", ".join(self._to)
113
        msg.preamble = "You need a MIME enabled mail reader to see this message"
114
        # Send message
115
        msg = msg.as_string()
116
        server = smtplib.SMTP(self._smtpServer)
117
        server.sendmail(self._from, self._to, msg)
118
        server.quit()
119
 
120
    def setSubject(self, subject):
121
        """
122
        Set the subject of the email message.
123
        """
124
        self._subject = subject
125
 
126
    def setFrom(self, address):
127
        """
128
        Set the email sender.
129
        """
130
        if not self.validateEmailAddress(address):
131
            raise Exception("Invalid email address '%s'" % address)
132
        self._from = address
133
 
134
    def clearRecipients(self):
135
        """
136
        Remove all currently defined recipients for
137
        the email message.
138
        """
139
        self._to = []
140
 
141
    def addRecipient(self, address):
142
        """
143
        Add a new recipient to the email message.
144
        """
145
        if not self.validateEmailAddress(address):
146
            raise Exception("Invalid email address '%s'" % address)
147
        self._to.append(address)
148
 
149
    def setTextBody(self, body):
150
        """
151
        Set the plain text body of the email message.
152
        """
153
        self._textBody = body
154
 
155
    def setHtmlBody(self, body):
156
        """
157
        Set the HTML portion of the email message.
158
        """
159
        self._htmlBody = body
160
 
161
    def clearAttachments(self):
162
        """
163
        Remove all file attachments.
164
        """
165
        self._attach = []
166
 
167
    def addAttachment(self, fname, attachname=None):
168
        """
169
        Add a file attachment to this email message.
170
 
171
        @param fname: The full path and file name of the file
172
                      to attach.
173
        @type fname: String
174
        @param attachname: This will be the name of the file in
175
                           the email message if set.  If not set
176
                           then the filename will be taken from
177
                           the fname parameter above.
178
        @type attachname: String
179
        """
180
        if fname is None:
181
            return
182
        self._attach.append( (fname, attachname) )
183
 
184
    def validateEmailAddress(self, address):
185
        """
186
        Validate the specified email address.
187
 
188
        @return: True if valid, False otherwise
189
        @rtype: Boolean
190
        """
191
        if self._reEmail.search(address) is None:
192
            return False
193
        return True
194
 
195
if __name__ == "__main__":
196
    # Run some tests
197
    DataService.initialize(db_hostname="localhost")
198
    currentTime = datetime.datetime.date(datetime.datetime.now())
199
    previousDay = datetime.datetime(currentTime.year,currentTime.month, currentTime.day, 0, 0)- timedelta(days=1)
200
    mTo = session.query(Users.email).filter(Users.mobile_number == None).filter(Users.created >= previousDay).all()
201
    #mTo = ["manish.sharma@shop2020.in", "manas.kapoor@shop2020.in"]
202
    mFrom = "ProfitMandi<help@profitmandi.com>"
203
    #print mTo
204
    #mTo = ["manish.sharma@shop2020.in", "sandeep.sachdeva@shop2020.in", "chaitnaya.vats@shop2020.in", "manoj.kumar@shop2020.in", "chandan.kumar@shop2020.in", "khushal.bhatia@shop2020.in", "yukti.jain@shop2020.in", "ankush.dhingra@shop2020.in", "rajneesh.arora@shop2020.in", "kshitij.sood@shop2020.in", "anikendra.das@shop2020.in"]
205
 
206
    for receipient in mTo:
207
        m = Email('localhost')
208
        m.setFrom(mFrom)
209
        print receipient[0]
210
        m.addRecipient(receipient[0])
211
        #print receipient
212
        message="""
213
<html>
214
    <body>
215
    <pre>		
216
    Dear Customer,
217
 
218
Thanks for showing your interest in Profitmandi android App.
219
 
220
This app is useful for frequent buyers of mobiles, tabs ad related products. Profitmandi recommends the most profitable online deals.
221
 
222
Only users having an invite code can use this app.
223
 
224
Request you to please provide your contact no so that we can get in touch with you and activate you on this app.
225
 
226
Regards,
227
Profitmandi Team
228
+91-8826894203
229
</pre>
230
    </body>
231
    </html>"""
232
 
233
        m.setSubject("ProfitMandi")
234
        m.setTextBody(None)
235
        m.setHtmlBody(message)
236
        m.send()
237
 
238
    if session.is_active:
239
        print "session is active. closing it."
240
        session.close()