def test_multiple_to(self): to = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] msg = Message(self.fromaddr, to, self.subject, self.bodyplain) txt = msg.as_string() result = re.search("^To: (.*)$", txt, re.M) self.assertTrue(result) self.assertEqual(result.group(1), ", ".join(to))
def send_contact_email(self, request): try: data = json.loads(request.data.decode()) first_name = data["first_name"] last_name = data["last_name"] email = data["email"] content = data["content"] if re.search(r'[\w.-]+@[\w.-]+.\w+', email): message = Message(From=self.email, To="Support-Codex-Contact") message.Subject = "Feedback " + first_name message.Html = """<p>Stock Prediction!<br>"""+\ """<br>"""+"Name : "+first_name +" "+last_name+"""<br>"""+ \ """<br>""" + "Email : " + email + """<br><br><br> """ + \ content server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(self.email, self.password) server.sendmail(self.email, self.email, message.as_string()) return {"status": "True"} else: return {"msg": "invalid email", "status": "False"} except Exception as e: generate_log('get_user_profile', str(e), str(request))
def send_email(user, pwd, recipient, subject, body): gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body message = Message(From=user, To=recipient) message.Subject = subject message.Html = body # Prepare actual message #message = """From: %s\nTo: %s\nSubject: %s\n\n%s #""" % (FROM, ", ".join(TO), SUBJECT, TEXT) #print(message) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() print("tls started") server.login(gmail_user, gmail_pwd) print("log in succesfull") server.sendmail(FROM, TO, message.as_string()) print('successfully sent the mail') server.close() print("server closed") except smtplib.SMTPException as error: print(str(error)) print("fail")
def test_html(self): msg = Message(self.fromaddr, self.toaddr, self.subject, bodyhtml=self.bodyhtml) txt = msg.as_string() result = re.search("^Content-Type: text/html;", txt, re.M) self.assertTrue(result)
def test_many_attachments(self): msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain, self.bodyhtml, self.attachments) txt = msg.as_string() pattern = re.compile("^Content-Disposition: attachment;", re.M) count = 0 for match in pattern.finditer(txt): count += 1 self.assertEqual(count, len(self.attachments))
def test_message_as_string(self): msg = Message( To='*****@*****.**', From='*****@*****.**', Subject='Test Message', Text='This is just a test message.', Html='<body><p>This is just a test message.</p></body>', ) msg.header('Message-ID', make_msgid()) s = msg.as_string() assert type(s) == str
def test_attach_pdf(self): att = list(filter(lambda s: s.endswith(".pdf"), self.attachments)) msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain, self.bodyhtml, att) txt = msg.as_string() result = re.search("^Content-Type: application/pdf", txt, re.M) self.assertTrue(result) pdf = get_attachment(txt, att[0]) with open(att[0], 'rb') as fp: orig = fp.read() self.assertEqual(orig, pdf)
def test_attach_image(self): att = list(filter(lambda s: s.endswith(".jpg"), self.attachments)) msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain, self.bodyhtml, att) txt = msg.as_string() result = re.search("^Content-Type: image/jpeg", txt, re.M) self.assertTrue(result) result = re.search("^Content-ID: <image\d+>", txt, re.M) self.assertTrue(result) img = get_attachment(txt, att[0]) with open(att[0], 'rb') as fp: orig = fp.read() self.assertEqual(orig, img)
def SendMail(MailConfig, Content, filename=None): message = Message(From=MailConfig.SENDOR, To=MailConfig.RECEIEVERS, charset="utf-8") message.Subject = MailConfig.SUBJECT message.Html = Content if filename != None: message.attach(filename) server = smtplib.SMTP(MailConfig.SMTPSETTING) server.starttls() server.sendmail(MailConfig.SENDOR, MailConfig.RECEIEVERS.split(";"), message.as_string()) server.quit()
def newemail(error): #Currently setup for gmail server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("youremail", "YOURPASSWORD") fp = open(outputTxt) message = Message(From="SENDEREMAIL", To="RECIEVEREMAIL", charset="utf-8") message.Subject = 'Service Validation has FAILED!!!' message.Body ='\n' + error + '\n'.join(fp.readlines()) #message.Body = 'Hello, \n\n The validation job has FAILED for Web Service Validation!!! Please refer to the error below for failed results\n'.join(fp.readlines()) fp.close() server.sendmail("YOUREMAIL", "RECEIVERSEMAIL", message.as_string()) server.quit()
def test_plain_and_html(self): msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain, self.bodyhtml) txt = msg.as_string() result = re.search("^Content-Type: multipart/alternative;", txt, re.M) self.assertTrue(result)
def test_plain(self): msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain) txt = msg.as_string() result = re.search("^Content-Type: text/plain;", txt, re.M) self.assertTrue(result)
def test_subject(self): msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain) txt = msg.as_string() result = re.search("^Subject: (.*)$".format(self.subject), txt, re.M) self.assertTrue(result) self.assertEqual(result.group(1), self.subject)
def sendforgetemail(self, request): try: data = json.loads(request.data.decode()) email = data["email"] record = self.mongoObj.ReadValue("users", email) if (record != None): message = Message(From=self.email, To=email) message.Subject = "Change Password" # message.Html = """<p>Hi!<br> # Welcome to Stock Prediction<br> # Here is the link """+ self.forgot_passwordLink + (str(base64.b64encode(bytes(email, "utf-8")).decode("utf-8"))).replace("=","~") + """ to change your password""" message.Html = """ <!DOCTYPE html> <html> <head> <style> body{ font-family: sans-serif; } .main{ background-color : #f3f7fa; height:300px; padding: 25px 250px; } .main h1{ color : #0070c9; text-align: center; } .sub-main{ padding: 25px 50px; background-color:#FFF; } .main .sub-main h1{ text-align: center; color : #46555d; font-weight:200; } .main .sub-main p{ text-align: center; color:#46555d; font-size:14px; } .main .sub-main img{ display:block; margin-left:auto;margin-right:auto;width:10%;height:10%; } </style> </head> <body> <div class="main" style=" background-color : #f3f7fa;height:300px;padding: 25px 250px;"> <h1 style="color : #0070c9;text-align: center;>Codex</h1> <div class="sub-main" style="padding: 25px 50px;background-color:#FFF;"> <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;" src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' /> <h1 style="text-align: center;color : #46555d;font-weight:200;">Reset Your Codex Password</h1> <hr> <p style=" text-align: center;color:#46555d;font-size:14px;">If this request is not from you, you can ignore this message and your account will still be secure.</p> <p>Here is the link : <br>""" + self.forgot_passwordLink + ( str( base64.b64encode(bytes( email, "utf-8")).decode("utf-8"))).replace( "=", "~") + """ to change your password </p> </div> </div> </body> </html> """ server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(self.email, self.password) server.sendmail(self.email, email, message.as_string()) return {"status": "True"} else: return {"msg": "invalid email", "status": "False"} except Exception as e: generate_log('sendforgetemail', str(e), str(request))
def register(self, request): data = json.loads(request.data.decode()) try: exists = self.mongoObj.ReadValue("users", data['email']) if exists != None: return {"msg": "Email already exist", "status": "False"} else: dic = { "user_id": data['email'], "password": data['password'], "firstname": data['firstname'], 'lastname': data['lastname'], "status": "0", "mobile": "", "skype": "", "phone": "", "gender": "" } self.mongoObj.WriteValue("users", data['email'], dic) # mongodb.WriteValue("users", data['email'], dic) email = data['email'] message = Message(From=self.email, To=email) message.Subject = "Codex Email Verification" message.Html = """ <!DOCTYPE html> <html> <head> <style> body{ font-family: sans-serif; } .main{ background-color : #f3f7fa; height:300px; padding: 25px 250px; } .main h1{ color : #0070c9; text-align: center; } .sub-main{ padding: 25px 50px; background-color:#FFF; } .main .sub-main h1{ text-align: center; color : #46555d; font-weight:200; } .main .sub-main p{ text-align: center; color:#46555d; font-size:14px; } .main .sub-main img{ display:block; margin-left:auto;margin-right:auto;width:10%;height:10%; } </style> </head> <body> <div class="main" style="background-color : #f3f7fa;height:300px;padding: 25px 250px;"> <h1 style=" color : #0070c9;text-align: center;">Codex</h1> <div class="sub-main" style="padding: 25px 50px;background-color:#FFF;"> <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;" src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' /> <h1 style=" text-align: center;color : #46555d;font-weight:200;">Welcome to Codex</h1> <hr> <p style=" text-align: center;color:#46555d;font-size:14px;">Please wait for registration approval from Codex team</p> </div> </div> </body> </html> """ server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(self.email, self.password) server.sendmail(self.email, email, message.as_string()) sender = self.email gmail_password = self.password dr_tariq_team = self.email_ids COMMASPACE = ', ' recipients = dr_tariq_team # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = 'Email Verification' outer['To'] = COMMASPACE.join(recipients) outer['From'] = sender message = """ <!DOCTYPE html> <html> <head> <style> @import url('https://fonts.googleapis.com/css?family=Open+Sans'); body{ font-family: sans-serif; } .main{ background-color : #f3f7fa; height:350px; padding: 25px 250px; } .main h1{ color : #0070c9; text-align: center; } .sub-main{ padding: 25px 50px; background-color:#FFF; } .main .sub-main h1{ text-align: center; color : #46555d; font-weight:200; } .main .sub-main p{ text-align: center; color:#46555d; font-size:14px; } .main .sub-main img{ display:block; margin-left:auto;margin-right:auto;width:10%;height:10%; } </style> </head> <body> <div class="main" style=" background-color : #f3f7fa; height:350px; padding: 25px 250px;"> <h1 style="color : #0070c9; text-align: center;">Codex</h1> <div class="sub-main" style=" padding: 25px 50px; background-color:#FFF;"> <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;" src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' /> <h1 style="text-align: center;color : #46555d;font-weight:200;">New Codex User</h1> <hr> <p style=" text-align: center;color:#46555d; font-size:14px;"> Email Address : """ + data['email'] + """<br> Date of Registration : """ + str( datetime.datetime.now().date() ) + """<br> Please Authorize """ + data[ 'email'] + """ to use Codex (Stock Prediction System) by verifying him on the given link:<br> """ + self.reg_emailLink + ( str( base64.b64encode(bytes( email, "utf-8")).decode("utf-8"))).replace( "=", "~") + """ </div> </div> </body> </html> """ # message = """<p> Email Address : """+data['email']+"""<br> # Date of Registration : """ + str(datetime.datetime.now().date()) + """<br> Please Authorize """ \ # + data['email'] + """ to use Stock Prediction System by verifying him on the given link: <br> """ \ # + self.reg_emailLink + ( str(base64.b64encode(bytes(email, "utf-8")).decode("utf-8"))).replace("=", "~") outer.attach(MIMEText(message, 'html')) outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' composed = outer.as_string() # Send the email with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login(sender, gmail_password) s.sendmail(sender, recipients, composed) s.close() print("Email sent!") return {"status": "True"} except Exception as e: generate_log('register', str(e), str(request))
def verify(self, request): data = json.loads(request.data.decode()) try: email = base64.b64decode( (bytes(str(data["email"]).replace("~", "="), "utf-8"))).decode("utf-8") record = self.mongoObj.ReadValue("users", email) if (record != None): record = ast.literal_eval(record["Data"]) record["status"] = "1" self.mongoObj.UpdateValue("users", email, record) message = Message(From=self.email, To=email) message.Subject = "Stock Prediction Account Approved" # message.Html = """<p>Dear """+ record['firstname'] + """!<br> # Your Stock Prediction System account has been approved successfully<br> # Here is the link """ + self.sp_link + """ to Access SP System""" message.Html = """ <!DOCTYPE html> <html> <head> <style> @import url('https://fonts.googleapis.com/css?family=Open+Sans'); body{ font-family: sans-serif; } .main{ background-color : #f3f7fa; height:300px; padding: 25px 250px; } .main h1{ color : #0070c9; text-align: center; } .sub-main{ padding: 25px 50px; background-color:#FFF; } .main .sub-main h1{ text-align: center; color : #46555d; font-weight:200; } .main .sub-main p{ text-align: center; color:#46555d; font-size:14px; } .main .sub-main img{ display:block; margin-left:auto;margin-right:auto;width:10%;height:10%; } </style> </head> <body> <div class="main" style=" background-color : #f3f7fa;height:300px; padding: 25px 250px;"> <h1 style="color : #0070c9;text-align: center;">Codex</h1> <div class="sub-main" style="padding: 25px 50px; background-color:#FFF;"> <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;" src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' /> <h1 style="text-align: center;color : #46555d;font-weight:200;">Account Approved</h1> <hr> <p style=" text-align: center;color:#46555d;font-size:14px;"><b>Dear """ + record[ 'user_id'] + """ !</b> Your account has been approved successfully, Here is the link """ + self.sp_link + """ to Access Codex </p> </div> </div> </body> </html> """ server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(self.email, self.password) server.sendmail(self.email, email, message.as_string()) return {"status": "True"} else: return {"msg": "invalid email", "status": "False"} except Exception as e: generate_log('verify', str(e), str(request)) return {"msg": "invalid email", "status": "False"}