Subversion Repositories SmartDukaan

Rev

Rev 15385 | Rev 15417 | Go to most recent revision | Details | Compare with Previous | 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])?)$")
15416 manish.sha 43
        self._bcc = ['manish.sharma@shop2020.in'] 
15385 manish.sha 44
        self.clearRecipients()
45
        self.clearAttachments()
46
 
47
    def send(self):
48
        """
49
        Send the email message represented by this object.
50
        """
51
        # Validate message
52
        if self._textBody is None and self._htmlBody is None:
53
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
54
        if len(self._to) == 0:
55
            raise Exception("Must specify at least one recipient")
56
 
57
        # Create the message part
58
        if self._textBody is not None and self._htmlBody is None:
59
            msg = MIMEText(self._textBody, "plain")
60
        elif self._textBody is None and self._htmlBody is not None:
61
            msg = MIMEText(self._htmlBody, "html")
62
        else:
63
            msg = MIMEMultipart("alternative")
64
            msg.attach(MIMEText(self._textBody, "plain"))
65
            msg.attach(MIMEText(self._htmlBody, "html"))
66
        # Add attachments, if any
67
        if len(self._attach) != 0:
68
            tmpmsg = msg
69
            msg = MIMEMultipart()
70
            msg.attach(tmpmsg)
71
        for fname,attachname in self._attach:
72
            if not os.path.exists(fname):
73
                print "File '%s' does not exist.  Not attaching to email." % fname
74
                continue
75
            if not os.path.isfile(fname):
76
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
77
                continue
78
            # Guess at encoding type
79
            ctype, encoding = mimetypes.guess_type(fname)
80
            if ctype is None or encoding is not None:
81
                # No guess could be made so use a binary type.
82
                ctype = 'application/octet-stream'
83
            maintype, subtype = ctype.split('/', 1)
84
            if maintype == 'text':
85
                fp = open(fname)
86
                attach = MIMEText(fp.read(), _subtype=subtype)
87
                fp.close()
88
            elif maintype == 'image':
89
                fp = open(fname, 'rb')
90
                attach = MIMEImage(fp.read(), _subtype=subtype)
91
                fp.close()
92
            elif maintype == 'audio':
93
                fp = open(fname, 'rb')
94
                attach = MIMEAudio(fp.read(), _subtype=subtype)
95
                fp.close()
96
            else:
97
                fp = open(fname, 'rb')
98
                attach = MIMEBase(maintype, subtype)
99
                attach.set_payload(fp.read())
100
                fp.close()
101
                # Encode the payload using Base64
102
                encoders.encode_base64(attach)
103
            # Set the filename parameter
104
            if attachname is None:
105
                filename = os.path.basename(fname)
106
            else:
107
                filename = attachname
108
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
109
            msg.attach(attach)
110
        # Some header stuff
111
        msg['Subject'] = self._subject
112
        msg['From'] = self._from
113
        msg['To'] = ", ".join(self._to)
15416 manish.sha 114
        msg['Bcc'] = ", ".join(self._bcc)
15385 manish.sha 115
        msg.preamble = "You need a MIME enabled mail reader to see this message"
116
        # Send message
117
        msg = msg.as_string()
118
        server = smtplib.SMTP(self._smtpServer)
119
        server.sendmail(self._from, self._to, msg)
120
        server.quit()
121
 
122
    def setSubject(self, subject):
123
        """
124
        Set the subject of the email message.
125
        """
126
        self._subject = subject
127
 
128
    def setFrom(self, address):
129
        """
130
        Set the email sender.
131
        """
132
        if not self.validateEmailAddress(address):
133
            raise Exception("Invalid email address '%s'" % address)
134
        self._from = address
135
 
136
    def clearRecipients(self):
137
        """
138
        Remove all currently defined recipients for
139
        the email message.
140
        """
141
        self._to = []
142
 
143
    def addRecipient(self, address):
144
        """
145
        Add a new recipient to the email message.
146
        """
147
        if not self.validateEmailAddress(address):
148
            raise Exception("Invalid email address '%s'" % address)
149
        self._to.append(address)
150
 
151
    def setTextBody(self, body):
152
        """
153
        Set the plain text body of the email message.
154
        """
155
        self._textBody = body
156
 
157
    def setHtmlBody(self, body):
158
        """
159
        Set the HTML portion of the email message.
160
        """
161
        self._htmlBody = body
162
 
163
    def clearAttachments(self):
164
        """
165
        Remove all file attachments.
166
        """
167
        self._attach = []
168
 
169
    def addAttachment(self, fname, attachname=None):
170
        """
171
        Add a file attachment to this email message.
172
 
173
        @param fname: The full path and file name of the file
174
                      to attach.
175
        @type fname: String
176
        @param attachname: This will be the name of the file in
177
                           the email message if set.  If not set
178
                           then the filename will be taken from
179
                           the fname parameter above.
180
        @type attachname: String
181
        """
182
        if fname is None:
183
            return
184
        self._attach.append( (fname, attachname) )
185
 
186
    def validateEmailAddress(self, address):
187
        """
188
        Validate the specified email address.
189
 
190
        @return: True if valid, False otherwise
191
        @rtype: Boolean
192
        """
193
        if self._reEmail.search(address) is None:
194
            return False
195
        return True
196
 
197
if __name__ == "__main__":
198
    # Run some tests
199
    DataService.initialize(db_hostname="localhost")
200
    currentTime = datetime.datetime.date(datetime.datetime.now())
201
    previousDay = datetime.datetime(currentTime.year,currentTime.month, currentTime.day, 0, 0)- timedelta(days=1)
202
    mTo = session.query(Users.email).filter(Users.mobile_number == None).filter(Users.created >= previousDay).all()
203
    #mTo = ["manish.sharma@shop2020.in", "manas.kapoor@shop2020.in"]
204
    mFrom = "ProfitMandi<help@profitmandi.com>"
205
    #print mTo
15416 manish.sha 206
    mTo = ["manish.sharma@shop2020.in"]
15385 manish.sha 207
 
208
    for receipient in mTo:
209
        m = Email('localhost')
210
        m.setFrom(mFrom)
211
        print receipient[0]
15416 manish.sha 212
        #m.addRecipient(receipient[0])
213
        m.addRecipient('manish.sharma@shop2020.in')
214
 
15385 manish.sha 215
        #print receipient
216
        message="""
217
<html>
218
    <body>
219
    <pre>		
220
    Dear Customer,
221
 
222
Thanks for showing your interest in Profitmandi android App.
223
 
224
This app is useful for frequent buyers of mobiles, tabs ad related products. Profitmandi recommends the most profitable online deals.
225
 
226
Only users having an invite code can use this app.
227
 
228
Request you to please provide your contact no so that we can get in touch with you and activate you on this app.
229
 
230
Regards,
231
Profitmandi Team
232
+91-8826894203
233
</pre>
234
    </body>
235
    </html>"""
236
 
237
        m.setSubject("ProfitMandi")
238
        m.setTextBody(None)
239
        m.setHtmlBody(message)
240
        m.send()
15416 manish.sha 241
        break
15385 manish.sha 242
 
243
    if session.is_active:
244
        print "session is active. closing it."
245
        session.close()