def validate_form(self): list_of_required_data = ['firstname', 'name', 'email', 'u_email', 'password', 'gender'] is_form_valid = True message = '' try: super(SignupHandler, self).validate_form(list_of_required_data) except InvalidFormError as e: message += e.message + '\n' is_form_valid = False finally: if not mail.is_email_valid(self.request.get('email')) or not mail.is_email_valid(self.request.get('u_email')): is_form_valid = False message += 'One of the email you entered is not valid \n' if not is_valid_ul_email(self.request.get('u_email')): is_form_valid = False message += 'The UL email entered is not valid' if not self.request.get('password') == self.request.get('confirm_password'): is_form_valid =False message += 'The two password didn\'t match \n' if not is_form_valid: raise InvalidFormError(message)
def send_mail(sender_email, reply_to_email, recipient_email, subject, plaintext_body): """Send an email using App Engine's Mail API. Arguments: sender_email: str. The email address of the sender. This should be in the form 'SENDER NAME <SENDER_EMAIL_ADDRESS>. recipient_email: str. The email address of the recipient. reply_to_email: str. The email address that the admin can reply to directly. subject: str. The subject of the email. plaintext_body: str. The text content of the email. Raises: ValueError: If 'sender_email', 'reply_to_email' or 'recipient_email' is invalid, according to App Engine. """ if not mail.is_email_valid(sender_email): raise ValueError('Malformed sender email address: %s' % sender_email) if not mail.is_email_valid(reply_to_email): raise ValueError('Malformed reply-to email address: %s' % reply_to_email) if not mail.is_email_valid(recipient_email): raise ValueError('Malformed recipient email address: %s' % recipient_email) message = mail.EmailMessage(sender=sender_email, reply_to=reply_to_email, to=recipient_email, subject=subject, body=plaintext_body) message.send()
def post(self): player = getPlayer(self.request) if player is None: return dict(error=True, errorMessage="You must be logged in to send challenges.") toEmail = self.request.get('to') fromEmail = self.request.get('from') message = self.request.get('message') if not fromEmail: return dict(error=True, errorMessage="You must provide a 'From:' email address") if not mail.is_email_valid(fromEmail): return dict(error=True, errorMessage="'%s' is not a valid email address"%fromEmail) if not toEmail: return dict(error=True, errorMessage="You must provide a 'To:' email address") if not mail.is_email_valid(toEmail): return dict(error=True, errorMessage="'%s' is not a valid email address"%toEmail) mail.send_mail(fromEmail, toEmail, "You have been challenged!", message) logging.info("Sending challenge from %s to %s with message %r", toEmail, fromEmail, message) return {'error':False, 'from':fromEmail, 'to':toEmail, 'message':message}
def valid_players(p1e, p2e, p1n, p2n): name_re = re.compile(r"^(?i)[a-z0-9_-]{1,20}$") if mail.is_email_valid(p1e) != True or mail.is_email_valid(p2e) != True: return False else: if not name_re.match(p1n) or not name_re.match(p2n): return False return True
def send_mail(sender_email, recipient_email, subject, plaintext_body, html_body, bcc_admin=False, reply_to_id=None): """Sends an email. The client is responsible for recording any audit logs. In general this function should only be called from email_manager._send_email(). Args: - sender_email: str. the email address of the sender. This should be in the form 'SENDER_NAME <SENDER_EMAIL_ADDRESS>'. - recipient_email: str. the email address of the recipient. - subject: str. The subject line of the email. - plaintext_body: str. The plaintext body of the email. - html_body: str. The HTML body of the email. Must fit in a datastore entity. - bcc_admin: bool. Whether to bcc feconf.ADMIN_EMAIL_ADDRESS on the email. - reply_to_id: str or None. The unique reply-to id used in reply-to email sent to recipient. Raises: Exception: if the configuration in feconf.py forbids emails from being sent. ValueError: if 'sender_email' or 'recipient_email' is invalid, according to App Engine. (and possibly other exceptions, due to mail.send_mail() failures) """ if not feconf.CAN_SEND_EMAILS: raise Exception('This app cannot send emails.') if not mail.is_email_valid(sender_email): raise ValueError('Malformed sender email address: %s' % sender_email) if not mail.is_email_valid(recipient_email): raise ValueError('Malformed recipient email address: %s' % recipient_email) msg = mail.EmailMessage(sender=sender_email, to=recipient_email, subject=subject, body=plaintext_body, html=html_body) if bcc_admin: msg.bcc = [feconf.ADMIN_EMAIL_ADDRESS] if reply_to_id: msg.reply_to = get_incoming_email_address(reply_to_id) # Send message. msg.send()
def send_mail(sender_email, recipient_email, subject, plaintext_body, html_body, bcc_admin=False): """Sends an email. The client is responsible for recording any audit logs. In general this function should only be called from email_manager._send_email(). Args: - sender_email: str. the email address of the sender. This should be in the form 'SENDER_NAME <SENDER_EMAIL_ADDRESS>'. - recipient_email: str. the email address of the recipient. - subject: str. The subject line of the email. - plaintext_body: str. The plaintext body of the email. - html_body: str. The HTML body of the email. Must fit in a datastore entity. - bcc_admin: bool. Whether to bcc feconf.ADMIN_EMAIL_ADDRESS on the email. Raises: Exception: if the configuration in feconf.py forbids emails from being sent. ValueError: if 'sender_email' or 'recipient_email' is invalid, according to App Engine. (and possibly other exceptions, due to mail.send_mail() failures) """ if not feconf.CAN_SEND_EMAILS_TO_USERS: raise Exception('This app cannot send emails to users.') if not mail.is_email_valid(sender_email): raise ValueError('Malformed sender email address: %s' % sender_email) if not mail.is_email_valid(recipient_email): raise ValueError('Malformed recipient email address: %s' % recipient_email) if bcc_admin: mail.send_mail(sender_email, recipient_email, subject, plaintext_body, html=html_body, bcc=[feconf.ADMIN_EMAIL_ADDRESS]) else: mail.send_mail(sender_email, recipient_email, subject, plaintext_body, html=html_body) counters.EMAILS_SENT.inc()
def send_activation(username, token, receiver_email): mail.is_email_valid(receiver_email) sender_address = "HaritzMedina-KaixoMundua <*****@*****.**>" subject = _("ConfirmRegistration") template = JINJA_ENVIRONMENT.get_template('static/templates/activationEmail.txt') link = "http://" + app_identity.get_default_version_hostname() + "/activate/" + str(token) body = template.render(link=link) # TODO Remove logging logging.info(body) mail.send_mail(sender_address, receiver_email, subject, body)
def get(self): password = self.request.get("password") if password == "dying": list = ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"] obj = MailingList() for _email in list: if mail.is_email_valid(_email): if obj.store(_email) is True: sender_address = "iPhone6 On sale Alert "+EMAIL_SENDER subject = "iPhone6 On sale Alert Service" body = """ Final entry: http://iphone6-hkgolden.appspot.com/ Backup1: http://iphone6-hkg.appspot.com/ Backup2: http://iphone6-707.appspot.com/ Login: https://reserve-jp.apple.com/JP/ja_JP/reserve/iPhone Check: https://reserve.cdn-apple.com/JP/ja_JP/reserve/iPhone/availability """ #mail.send_mail(sender_address,_email, subject, body) logging.info("Welcome letter sent to "+_email) self.redirect("/success") else: self.redirect("/failure#1")
def send_email(user_email, subject, body): """Helper function for sending emails. Args: user_email (string): Email of the recipient. subject (string): Email subject. body (basestring): Html body of the email. it can contain unicode characters and will be sent as a html mime type. """ sender = get_app_engine_email() if not mail.is_email_valid(user_email): current_app.logger.error( "Invalid email recipient: {}".format(user_email)) return if not sender: current_app.logger.error("APPENGINE_EMAIL setting is invalid.") return message = mail.EmailMessage(sender=sender, subject=subject) message.to = user_email message.body = "TODO: add email in text mode." message.html = body message.send()
def CmdWhitelistDo(from_name,msg): if not funcs.isAdmin(from_name): return 'you are not administrator' if GetCmdNum(msg) == 1: whitelist = funcs.getWhiteList() if whitelist is None or len(whitelist) == 0: retstr = 'whitelist is null' else: retstr = '' for item in whitelist: retstr += item + ',' return retstr if GetCmdNum(msg) != 3: return 'para error' cmd = GetCmdByNum(msg,2) gtalk = GetCmdByNum(msg,3) if not mail.is_email_valid(gtalk): return 'ERROR:gtalk is not email' if cmd == 'add': ret = funcs.addWhiteList(gtalk) if ret: return 'add %s to whitelist success' % gtalk else: return 'add %s to whitelist fail' % gtalk if cmd == 'del': ret = funcs.delWhiteList(gtalk) if ret: return 'delete %s from whitelist success' % gtalk else: return 'delete %s from whitelist fail' % gtalk return 'para error'
def post(self): args = password_reset_post.parse_args() email = args['email'] user = user_model.get_by_email(email) if user is None: api.abort(404, 'User not found') token = user.get_session_token(expiration=21600, password_reset=True) if mail.is_email_valid(config.get('mail_sender')): sender = config.get('mail_sender') else: app_id = app_identity.get_application_id() sender = "%s <noreply@%s.appspotmail.com>" % (app_id, app_id) try: message = mail.EmailMessage() message.sender = sender message.subject = 'Password reset request' message.to = email message.body = ''' You're receiving this email because you requested a password reset. Visit the following page to reset your password: %s?reset_token=%s ''' % (config.get('password_reset_url'), token) message.send() except: api.abort(500) return '', 200
def post(self): message = mail.InboundEmailMessage(self.request.body) ## Get the traderID from the post based on the email address and "forward" the email this_post = Post.query( Post.contact == message.to).order(-Post.engage).get() email_to = this_post.traderID if mail.is_email_valid(email_to): email_messages = message.bodies('text/plain') email = get_email_text("Post Reply") for content_type, msg in email_messages: full_message = mail.EmailMessage( sender="%s <%s@%s>" % (bitsettings.site_name, bitsettings.email_local, bitsettings.email_suffix), subject="%s %s - %s" % (bitsettings.email_subject, this_post.title, str(this_post.price)), to="%s <%s>" % (email_to.split('@')[0], email_to), reply_to=message.sender, body=email.find('header').text + "\n\n" + str(message.subject).upper() + "\n" + msg.decode() + "\n\n" + email.find('footer').text, ) full_message.send()
def post(self): user = users.get_current_user() if user: sale = db.get(self.request.get("key")) sellerName = User.gql("WHERE userid = '%s'" % (sale.sellerid)).get().name numberOfEmail = 0 numberOfFails = 0 for i in range(len(sale.buyersList)): userEmail = User.gql("WHERE userid = '%s'" % (sale.buyersList[i])).get().email userName = User.gql("WHERE userid = '%s'" % (sale.buyersList[i])).get().name if not mail.is_email_valid(userEmail): numberOfFails += 1 else: sender_address = "shirt-up Support <*****@*****.**>" subject = "Your shirt is ready for collection" body = """ Hi,%s: Your shirt is currently with %s.Please collect it soon. Thank you for using shirt-up!""" % (userName, sellerName) mail.send_mail(sender_address, userEmail, subject, body) numberOfEmail += 1 self.response.write("%s emails sent. %s emails failed to send" % (numberOfEmail, numberOfFails))
def post(self): sender = "*****@*****.**" to = self.request.post('to') error = False errorMsg = "" if not mail.is_email_valid(to): errorMsg = "to Email is invalid" error = True elif not self.request.post('subject'): errorMsg = "Subject is invalid" error = True if error: self.response.write(errorMsg) else: message = mail.EmailMessage() message.sender = sender message.to = to message.subject = self.request.post('subject') if self.request.post('ishtml'): message.html = self.request.post('body') else: message.body = self.request.post('body') if self.request.post('cc'): message.cc = self.request.post('cc') if self.request.post('bcc'): message.bcc = self.request.post('bcc') if self.request.post('reply_to'): message.reply_to = self.request.post('reply_to') message.send() self.response.write("Success")
def send_band_accepted_email(the_req, the_email, the_band): set_locale_for_user(the_req) if not mail.is_email_valid(the_email): return False message = mail.EmailMessage() message.sender = SENDER_EMAIL message.to = the_email message.subject = _('Gig-o-Matic: Confirmed!') # message.body = u""" # Hello! You have been confirmed as a member of {0} and can now start using Gig-o-Matic to manage your band life. # # http://gig-o-matic.appspot.com/band_info.html?bk={1} # # Thanks, # The Gig-o-Matic Team # # """.format(the_band.name, the_band.key.urlsafe()) message.body = _('member_confirmed_email').format(the_band.name, the_band.key.urlsafe()) try: message.send() except: logging.error('failed to send email!') return True
def send(to_emails, subject, template_name, template_params=None): """Send email to a set of users. Args: to_emails: An iterable of strings, each string containing one email address. subject: A string, the subject line of the email. template_name: Name of the Jinja template file(s) template_params: A dict of parameters used to populate the Jinja email content template(s). Raises: ValueError: On ill-formed email addresses. RuntimeError: On finding no templates matching template_name """ to_emails = list(to_emails) if not all([appengine_mail.is_email_valid(e) for e in to_emails]): raise ValueError('At least one email address in %s is not valid.' % to_emails) # pylint: disable=unbalanced-tuple-unpacking if template_params is None: template_params = {} html_content = Template.evaluate_template(template_name, template_params) _AppEngineMailer.send(to_emails, subject, html_content) logging.info('Sent mail:\nsubject "%s"\nto %s\ncontent:\n%s;', subject, str(to_emails), html_content)
def post(self): loadlang(self.request) email = self.request.get('reply_email') message = self.request.get('message') isdonation = self.request.get('donation') page_header = S.mail_sent_ok page_content = '' if isdonation != 'true': if not mail.is_email_valid(email): page_header = S.mail_invalid_address elif len(message) == 0: page_header = S.mail_invalid_content else: body = "Message from %s \n %s" % (email, message) mail.send_mail('*****@*****.**', '*****@*****.**', S.mail_subject_contact, body) else: body = "Message from %s \n %s" % (email, message) mail.send_mail('*****@*****.**', '*****@*****.**', S.mail_subject_donate, body) template_values = { 'page_header': page_header, 'page_content': page_content } template = jinja_environment.get_template(common.index_page) self.response.out.write( template.render(loadindexpagevars(template_values)))
def email(address, subject, body): if not mail.is_email_valid(address): logging.info('Invalid email address %s' % (address)) return sender_address = "Pregnansi Support<*****@*****.**>" mail.send_mail(sender_address, address, subject, body)
def CmdWhitelistDo(from_name, msg): if not funcs.isAdmin(from_name): return 'you are not administrator' if GetCmdNum(msg) == 1: whitelist = funcs.getWhiteList() if whitelist is None or len(whitelist) == 0: retstr = 'whitelist is null' else: retstr = '' for item in whitelist: retstr += item + ',' return retstr if GetCmdNum(msg) != 3: return 'para error' cmd = GetCmdByNum(msg, 2) gtalk = GetCmdByNum(msg, 3) if not mail.is_email_valid(gtalk): return 'ERROR:gtalk is not email' if cmd == 'add': ret = funcs.addWhiteList(gtalk) if ret: return 'add %s to whitelist success' % gtalk else: return 'add %s to whitelist fail' % gtalk if cmd == 'del': ret = funcs.delWhiteList(gtalk) if ret: return 'delete %s from whitelist success' % gtalk else: return 'delete %s from whitelist fail' % gtalk return 'para error'
def regist(self): # アドレスチェック if not mail.is_email_valid(self.request.get('mail')): return {'success': False, 'MSG': 'It is wrong e-mail address.'} # 既存チェック query = models.Account.queryForRegist(self.request.get('mail')) if query.count() > 0: return {'success': False, 'MSG': 'It is already registered.'} # パラメータからデータ取り出し vals = {} for it in self.request.arguments(): vals[it] = self.request.get(it) # アカウントレコード作成 rec = models.Account.newdefault(vals, 0) rec.put() # メール送信 sender = '*****@*****.**' receiver = rec.mail subject = 'Degino conformation' body = ''' [Degino 認証] 次の URL をクリックして、登録手続きを完了してください。 http://%s/Auth?CONFORM=%s ''' % ('app.degino.com', rec.authkey) mail.send_mail(sender, receiver, subject, body) return {'success': True}
def post(self): user = users.get_current_user() if user is None: login_url = users.create_login_url(self.request.uri) self.redirect(login_url) return to_addr = self.request.get('content') print to_addr if not mail.is_email_valid(to_addr): # Return an error message... return message = mail.EmailMessage() message.sender = user.email() message.to = to_addr message.body = """ I've invited you to Example.com! To accept this invitation, click the following link, or copy and paste the URL into your browser's address bar: """ message.send() self.redirect('/')
def post(self): try: data = json.loads(self.request.body) except: logging.Warning("Bad JSON request") self.error(400) self.response.write('Invalid request') return # ugh, consider using validictory? if ('email' not in data or 'token' not in data or 'amount' not in data or 'userinfo' not in data or 'occupation' not in data['userinfo'] or 'employer' not in data['userinfo'] or 'phone' not in data['userinfo'] or 'target' not in data['userinfo']): self.error(400) self.response.write('Invalid request') return email = data['email'] token = data['token'] amount = data['amount'] name = data.get('name', '') occupation = data['userinfo']['occupation'] employer = data['userinfo']['employer'] phone = data['userinfo']['phone'] target = data['userinfo']['target'] try: amount = int(amount) except ValueError: self.error(400) self.response.write('Invalid request') return if not (email and token and amount and occupation and employer and target): self.error(400) self.response.write('Invalid request: missing field') return if not mail.is_email_valid(email): self.error(400) self.response.write('Invalid request: Bad email address') return customer = stripe.Customer.create(card=token, email=email) pledge = model.addPledge( email=email, stripe_customer_id=customer.id, amount_cents=amount, occupation=occupation, employer=employer, phone=phone, target=target, note=self.request.get("note")) # Add thank you email to a task queue deferred.defer(send_thank_you, name or email, email, pledge.url_nonce, amount, _queue="mail") self.response.write('Ok.')
def send_the_pending_email(the_req, the_email_address, the_confirm_link): if not mail.is_email_valid(the_email_address): return False set_locale_for_user(the_req) message = mail.EmailMessage() message.sender = SENDER_EMAIL message.to = the_email_address message.subject = _('Gig-o-Matic Confirm Email Address') # message.body = u""" # Hi there! Someone has requested to change their Gig-o-Matic ID to this email address. # If it's you, please click the link to confirm. If not, just ignore this and it will # go away. # # {0} # # Thanks, # Team Gig-o-Matic # # """.format(the_confirm_link) message.body=_('confirm_email_address_email').format(the_confirm_link) try: message.send() except: logging.error('failed to send email!') return True
def post(self): data = json.loads (self.request.body) user = users.get_current_user() sender = None if user is None: sender = data.get ("sender") else: sender = user.email () body = data.get ("body", '') name = data.get ("name") subject = data.get ("subject", '') if sender is None or not mail.is_email_valid (sender): self.response.status = 401 self.response.write ("Unauthorized") return to_addr = "*****@*****.**" if not name is None: body = "Message from " + name + ": \n" + body message = mail.EmailMessage () message.sender = sender message.subject = subject message.to = to_addr message.body = body message.send()
def notify(self,comment): sbody=self.sbody.decode('utf-8') bbody=self.bbody.decode('utf-8') if self.blog.comment_notify_mail and self.blog.owner and not users.is_current_user_admin() : sbody=sbody%{'title':comment.entry.title, 'author':comment.author, 'weburl':comment.weburl, 'email':comment.email, 'content':comment.content, 'commenturl':comment.entry.fullurl+"#comment-"+str(comment.key().id()) } mail.send_mail_to_admins(self.blog.owner.email(),'Comments:'+comment.entry.title, sbody,reply_to=comment.email) #reply comment mail notify refers = re.findall(r'#comment-(\d+)', comment.content) if len(refers)!=0: replyIDs=[int(a) for a in refers] commentlist=comment.entry.comments() emaillist=[c.email for c in commentlist if c.reply_notify_mail and c.key().id() in replyIDs] emaillist = {}.fromkeys(emaillist).keys() for refer in emaillist: if self.blog.owner and mail.is_email_valid(refer): emailbody = bbody%{'title':comment.entry.title, 'author':comment.author, 'weburl':comment.weburl, 'email':comment.email, 'content':comment.content, 'commenturl':comment.entry.fullurl+"#comment-"+str(comment.key().id()) } message = mail.EmailMessage(sender = self.blog.owner.email(),subject = 'Comments:'+comment.entry.title) message.to = refer message.body = emailbody message.send()
def sendTemplateEmail(to, mail_key, insert_classes, send_from_current, file_name, file_data): ''' to - the person being sent the email mail_key - lookup into the mail templates insert_classes - a (potentially empty) list of classes to add data into the subject and body. Notation is <python attr name>.. ''' template = MailTemplate().getMailTemplateByKey(mail_key) send_to = to if send_from_current: send_from = users.get_current_user().email() else: send_from = template.from_email if (send_to == ""): send_to = template.to_email if not mail.is_email_valid(send_to): # prompt user to enter a valid address raise Exception("Sending to email address is invalid") else: subject = template.subject body = template.body for class_in in insert_classes: body = renderText(body, class_in) subject = renderText(subject, class_in) if file_name <> None: #attach the file mail.send_mail(send_from, send_to, subject, body, attachments=[(file_name, file_data)]) else: mail.send_mail(send_from, send_to, subject, body)
def validate(display_name, email=None): if len(display_name) < 2: raise simpleeditions.RegisterError( 'Display name must be at least 2 characters long.') if len(display_name) > 25: raise simpleeditions.RegisterError( 'Display name may not be any longer than 25 characters.') if not re.match('[a-zA-Z][a-zA-Z0-9 ]+$', display_name): raise simpleeditions.RegisterError( 'The display name can only contain letters, numbers and ' 'spaces. The first character must be a letter.') qry = User.all(keys_only=True).filter('canonical_name', User.get_canonical_name(display_name)) if qry.get(): raise simpleeditions.RegisterError( 'That display name, or a very similar one, already exists.') if email: qry = User.all(keys_only=True).filter('email', email) if qry.get(): raise simpleeditions.RegisterError('E-mail is already in use.') if not mail.is_email_valid(email): raise ValueError('A valid e-mail address must be provided.')
def post(self, q): # takes input from user userMail = self.request.get("contact_email") name = self.request.get("contact_name") userMessage = self.request.get("contact_message") message = mail.EmailMessage( sender="goaweddingexpo.in: Contact Us<*****@*****.**>", subject="Contact") # not tested if not mail.is_email_valid(userMail): self.response.out.write("Wrong email! Check again!") message.to = userMail message.body = """Thank you! You have entered following information: Your mail: %s Name: %s Message: %s \nThank You For Contacting Goa Wedding Expo.""" % (userMail, name, userMessage) message.send() # self.response.out.write("Message sent to user!") contact_message = mail.EmailMessage(sender="*****@*****.**", subject="Contact") contact_message.to = "*****@*****.**" contact_message.body = """The Following person contacted: Mail: %s Name: %s Message: %s""" % (userMail, name, userMessage) contact_message.send() # self.response.out.write("Message sent to goa wedding expo admin!") self.response.out.write("sent")
def post(self, foto_key): #Send email to logged in user oUser = users.get_current_user() strMailto = oUser.email() #Get cc'ed users from form strMailcc = self.request.get('mailcc') if mail.is_email_valid(strMailcc): strMailto = strMailto + ',' + strMailcc #Retrieve message text strMailbody = cgi.escape(self.request.get('mailbody'), quote=True) if strMailbody =='': strMailbody = 'Checkout the attached foto I found on fotobox!' oMessage = mail.EmailMessage() oMessage.sender = SENDER #only allowed to send as application admin/owner oMessage.to =strMailto oMessage.subject = cgi.escape(self.request.get('mailsubject')) oMessage.body = strMailbody #Get foto Object oFoto = db.get(foto_key) strFotoname = oFoto.name #strip all spaces from foto.name strFotoname = re.sub(r'\s+', '', strFotoname) + '.png' #attach foto oMessage.attachments=[(strFotoname, oFoto.data)] #send message try: oMessage.send() except mail.Error, e: self.error(400) self.response.out.write('Error: ' + str(e))
def post(self): secret_code = self.request.get("secret") if secret_code != config.SECRET_CODE: self.response.out.write('fail1') return to_addr = self.request.get("to") from_addr = self.request.get("from") body = self.request.get("message") subject = self.request.get("subject") if not mail.is_email_valid(to_addr): # Return an error message... self.response.out.write('fail2') return message = mail.EmailMessage() message.sender = from_addr message.to = to_addr message.subject = subject message.body = body message.send() #self.response.out.write('success') template_values = {} path = os.path.join(os.path.dirname(__file__), 'success.html') self.response.out.write(template.render(path, template_values))
def CmdUserDo(from_name,msg): ret_str = u'init' if GetCmdNum(msg) != 2: return 'error:need user nickname or gtalk' nickname = GetCmdByNum(msg,2) if mail.is_email_valid(nickname): user = funcs.getUserByName(nickname) if user is None: user = funcs.getUserByNickname(nickname) else: user = funcs.getUserByNickname(nickname) if user is None: ret_str = u'CANT find user:%s' % nickname return ret_str.encode('utf-8') ret_str = u'%s' % user.nickname if funcs.isAdmin(from_name) or user.gtalk==from_name: ret_str += u'(%s)' % user.gtalk ret_str += u',在%s第%d个加入本群\n' % (funcs.getNatureTime(user.time),funcs.getUserNo(user.gtalk)) if funcs.isAdmin(from_name) or user.gtalk==from_name: ret_str += u'设置:' if user.recvOfflineMsg: ret_str += u'离线时接收消息' else: ret_str += u'离线时不接收消息' if user.recvOnlineMsg: ret_str += u',在线时接收消息\n' else: ret_str += u',在线时不接收消息\n' users_dict = funcs.getUserCountList() if user.gtalk in users_dict.keys(): user_data = users_dict[user.gtalk] ret_str += u'共发%d个消息,最后一次发消息在%s' % (user_data['count'],funcs.getNatureTime2(user_data['time'])) return ret_str.encode('utf-8')
def mail_sponsor_message(sponsor, award): sponsee = award.winner logging.debug("sending e-mail to %s", sponsor.email) if not mail.is_email_valid(sponsor.email): logging.error("%s is not valid", sponsor.email) return False message = mail.EmailMessage() message.sender = get_sender() message.subject = "Your PlopQuiz sponsorship has been awarded!" message.to = sponsor.email message.body = """ %s, Your PlopQuiz sponsorship has been earned by a student! %s has been awarded a sponsorship from your organization for exceptional performance in the %s quiz subject You can visit this student's profile at %s You can view the sponsorship on your profile at %s %s """ % (sponsor.fullname, sponsee.fullname, award.proficiency.name.upper(), "http://" + str(os.environ['HTTP_HOST']) + "/profile/" + sponsee.profile_path, "http://" + str(os.environ['HTTP_HOST']) + "/sponsors/" + sponsor.profile_path, mail_footer()) message.send()
def email_booking_to_patient(handler, booking, activation_url=None): ''' send booking info to patient, provider and us ''' patient = booking.patient.get() provider = booking.provider.get() to_address = patient.email # check email valid if not mail.is_email_valid(to_address): logging.warn('Email is not valid: %s -- trying anyway...' % to_address) # create message message = mail.EmailMessage() message.sender = "Veosan" + ' <' + VEOSAN_SUPPORT_ADDRESS + '>' message.to = to_address category_label = dict( util.get_all_categories_all_domains())[provider.category] message.subject = '%s - %s' % (_(u'Veosan Appointment'), _(category_label).capitalize()) kw = {'booking': booking, 'activation_url': activation_url} logging.debug('activation url for email: %s' % activation_url) message.body = render_booking_email_body(handler.jinja2, 'email/patient_booking.txt', **kw) try: logging.info('Sending booking email to provider %s' % patient.email) message.send() booking.email_sent_to_patient = True booking.put() except Exception as e: logging.error('Email to patient not sent. %s' % e)
def post(self): email_notification = EmailNotification() logging.debug(self.request.body) body = json.decode(self.request.body) email_notification.recipient_email = body["recipient_email"] logging.debug("recipient_email: %s", email_notification.recipient_email) email_notification.sender_name = body["sender_name"] logging.debug("sender_name: %s", email_notification.sender_name) email_notification.put() resp = { "recipient_email": email_notification.recipient_email, "sender_name": email_notification.sender_name } if not mail.is_email_valid(email_notification.recipient_email): self.response.write('Bad Email') else: sender = "%s <*****@*****.**>" % email_notification.sender_name subject, body, html = randMessage(email_notification.sender_name) logging.debug('Sending Email') sendEmailWithSendGrid(sender, email_notification.recipient_email, subject, body, html) # sendEmailWithGAEMailAPI(sender, email_notification.recipient_email, subject, body, html) logging.debug('Sending Response') self.response.write(json.encode(resp))
def post(self): if not self.request.get("email") or not self.request.get("password"): self.render_template("Error faltan campos") return email = self.request.get("email") password = self.request.get("password") if not mail.is_email_valid(email): self.render_template("Error:email no valido") return lon = len(password) if lon < 6 or lon > 30: self.render_template(u"Error:Contraseña tiene que tener un tamaño entre 6 y 30 caracteres") return u = todosmodelos.Usuarios.query( todosmodelos.Usuarios.email == email, todosmodelos.Usuarios.password == nueva_contra(password) ).get() if u: if u.token and not u.valida: self.render_template(u"Este email todavía no está validado, por favor revisa tu correo.") return self.session["usuario"] = u self.response.out.write(TEMPLATE_PRICIPAL % u.nombre) # self.redirect('/admintienda') else: self.render_template(u"Email o contraseña incorrecta.")
def emit(self, record): """ Send a log record via email (depending on level). :param record: Log record """ recipients = set() for email_level in self.levels_to_addresses: if record.levelno < email_level: continue # Need to send this record to the list recipients. for email in gutils.flatten(self.levels_to_addresses[email_level]): recipients.add(email) for r in recipients: if mail.is_email_valid(r): subject = '{} from {} (Ver {})'.format(record.levelname, self.app_id, self.app_ver) body = self.format(record) #noinspection PyBroadException try: mail.send_mail(self.sender, r, subject, body) except Exception: # If we cannot send an email just plow on but don't fail. pass
def new_registration_type(registration_type): form = RegistrationForm() if registration_type == 'sat_no_meal': session['registration_price'] = 1000 elif registration_type == 'sat_with_meal': session['registration_price'] = 1900 elif registration_type == 'full_no_meal': session['registration_price'] = 2000 elif registration_type == 'full_with_meal': session['registration_price'] = 2900 else: return render_template('404.html'), 404 if form.validate_on_submit(): if mail.is_email_valid(form.email.data): session['registration_type'] = registration_type session['first_name'] = form.first_name.data session['last_name'] = form.last_name.data session['mobile'] = form.mobile.data session['email'] = form.email.data session['sobriety_date'] = str(form.sobriety_date.data) session['ypaa_committee'] = form.ypaa_committee.data session['fellowship'] = form.fellowship.data session['special_needs'] = form.special_needs.data session['of_service'] = form.of_service.data session['country'] = form.country.data return redirect(url_for('new_registration_2', registration_type=registration_type)) else: flash('Invalid email address') return redirect(url_for('new_registration_type', registration_type=registration_type)) return render_template('new_registration_1.html', form=form, registration_type=registration_type)
def post(self): user = users.get_current_user() if user: userMail = self.request.get("mail") subject = self.request.get("subject") name = self.request.get("name") userMessage = self.request.get("message") message = mail.EmailMessage(sender="*****@*****.**", subject="Test") # not tested if not mail.is_email_valid(userMail): self.response.out.write("Check your email again") message.to = userMail message.body = """Thank you! You have entered following information: Your mail: %s Subject: %s Name: %s Message: %s""" % (userMail, subject, name, userMessage) message.send() template = env.get_template('message.html') self.response.write(template.render()) else: self.redirect(users.create_login_url('/'))
def get(self): email = self.request.get('email', None); results = {'success': False} if email is None or not mail.is_email_valid(email): logging.warn('Invalid email:%s', email) results['error'] = 'Invalid address.' else: user = users.get_current_user() playlist = model.Playlist.get_or_insert(user.user_id(), owner=user) if playlist.link: short_link = playlist.link else: short_link = GetShortUrl('http://party-box.appspot.com', str(playlist.key())) sender_address = 'PartyBox <*****@*****.**>' subject = 'Playlist Invitation' body = """ Hello %s,\n\n %s would like you to check out their playlist on PartyBox. You can add songs to the playlist, or vote on existing songs.\n\n %s """ % (email, user.email(), short_link) mail.send_mail(sender_address, email, subject, body) results['success'] = True self.response.out.write(json.dumps(results))
def post(self): fname=self.request.get('name') email=self.request.get('email') message=self.request.get('message') if not mail.is_email_valid(email): # prompt user to enter a valid address template = JINJA_ENVIRONMENT.get_template('templates/contactme.html') else: to_address = "[email protected] <*****@*****.**>" subject = "Thank you for contacting me!" body = """ Contact Information : Name : %s Email : %s Message : %s """ % (fname, email, message) # mail.send_mail(sender_address, user_address, subject, body) mail.send_mail(to_address, to_address, subject, body) logging.info(fname) logging.info(email) logging.info(message) template = JINJA_ENVIRONMENT.get_template('templates/submitted.html') options={ 'path': "/submitted.html" } self.response.write(template.render(options))
def send_invite_email(email): student = RoseboticsStudent.get_by_id(email) if student is None: return if mail.is_email_valid(student.alt_email): email = [email, student.alt_email] message = mail.EmailMessage( sender="*****@*****.**") message.to = email message.subject = "ROSEbotics Team Invite" message.body = """ Hello, You've been invited to join a ROSEbotics Team! Teams is a place where you can create study groups and monitor others progress within the courses on the website. You can see your pending invites at: http://www.rosebotics.org/teams/#/invites/ Happy Learning! -- The ROSEbotics Team """.strip() try: message.send() logging.info("Invite Email should have been sent to: " + str(email)) except Exception, e: logging.warn("Invite Email not sent to: " + str(email) + str(e))
def post(self): objjson=json.loads(cgi.escape(self.request.body)) if not objjson.has_key("email"): self.resjsonerror('Error: falta email') return email = objjson["email"] if not mail.is_email_valid(email): self.resjsonerror('Error:email no valido') return u = todosmodelos.Usuarios.query(todosmodelos.Usuarios.email==email).get() if not u: self.resjsonerror('No existe ningún usuario con email %s' % email) return user_id = u.key.id() if u.valida and u.token: token=u.token else: token=nuevo_token() u.token=token u.put() verification_url = self.uri_for('verification', type='p', user_id=user_id, signup_token=token, _full=True) #msg = 'Send an email to user in order to reset their password. \ # They will be able to do so by visiting <a href="{url}">Cambiar contraseña</a>' msg = u'Mensaje de Pagina web Pizza para cambiar su contraseña, pulse en el link para dirigirse a la página web y \ <a href="{url}">Cambiar contraseña</a>. Si usted no solicitó el cambio de contraseña por favor ignore este mensaje.' mensaje = mail.EmailMessage() mensaje.sender = "Pizzaweb <*****@*****.**>" mensaje.to = "%s <%s>" % (u.nombre,email) mensaje.html=msg.format(url=verification_url) mensaje.send() self.resjsonok("se ha enviado un mensaje a %s con un link ( %s ) de confirmación, por favor revise su correo." % (email,verification_url))
def get(self): game_name = self.request.get("game_name") or os.environ["default_game_name"] if Game.has_started(game_name): self.response.out.write("Already started") return users = Player.in_game(game_name).fetch(None) shuffle(users) assassin = users[len(users) - 1] for user in users: mission = Mission(parent=Game.get_key(game_name)) mission.assassin = assassin.nickname mission.victim = user.nickname mission.put() user.numkills = 0 user.publickills = 0 user.publiclist = 0 user.put() assassin = user # Send email to all players if not mail.is_email_valid(user.email): self.response.out.write("Warning: Invalid email: " + user.email) else: sender_address = os.environ["start_email_sender"] subject = "[League of Interns] Let the games begin!" html = os.environ["start_email_body"] % game_name body = re.sub("<[^<]+?>", "", html) mail.send_mail(sender_address, user.email, subject, body, html=html) self.response.out.write("Done")
def post(self): # Get information from the signup forms. first_name = self.request.get('firstname') last_name = self.request.get('lastname') email = self.request.get('email') password = self.request.get('password') address = self.request.get('address') gender = self.request.get('gender') birthday = self.request.get('birthday') interests = self.request.get('interests') # Use mail API to check if the email is valid. if not mail.is_email_valid(email): error = "The provided email is not valid." self.render("signup.html", error=error) # Check if the email is in user database. user = database.User.all().filter('email =', email).get() if user: error = "You have already signed up. Please go to login page." self.render("signup.html", error=error) # Store new user in the database and send email to the user. else: self.send_signup(email, first_name) database.User(first_name=first_name, last_name=last_name, email=email, password=hash_str(password.strip()), address=address, gender=gender, birthday=birthday, interests=interests, offensive_score=0, no_of_quotes=0).put() self.redirect('/login')
def send_the_new_member_email(the_locale, the_email_address, new_member, the_band): if not mail.is_email_valid(the_email_address): return False i18n.get_i18n().set_locale(the_locale) message = mail.EmailMessage() message.sender = SENDER_EMAIL message.to = the_email_address message.subject = _('Gig-o-Matic New Member for band {0})').format(the_band.name) # message.body = u""" # Hello! A new member {0} has signed up for your band {1}. Please log in and # confirm the membership. # # http://gig-o-matic.appspot.com/band_info.html?bk={2} # # Thanks, # The Gig-o-Matic Team # # """.format(new_member.name, the_band.name, the_band.key.urlsafe()) message.body = _('new_member_email').format(new_member.name, the_band.name, the_band.key.urlsafe()) try: message.send() except: logging.error('failed to send email!') return True
def sendEmail(self, email, ticketNum, blurb, imageName): if not mail.is_email_valid(email): self.response.write("<html><body>hello</body></html>") #prompt user to enter a valid address else: message = mail.EmailMessage(sender="John Cleese <*****@*****.**>", subject="Your Asha for Education ticket purchase was successful!") message.to = email message.body = """ Hello, Your request for a ticket with Asha for Education has been approved. Please print the attached ticket and bring it with you to the event. Thank you. Asha for Education """ # Generate image string x = barcode.generate(ticketNum, blurb, imageName) output = StringIO.StringIO() x.save(output, "PNG") message.attachments = [('ticket.png', output.getvalue())] output.close() message.send()
def send_registration_email(the_req, the_email, the_url, the_locale_override=None): set_locale_for_user(the_req, the_locale_override) if not mail.is_email_valid(the_email): return False message = mail.EmailMessage() message.sender = SENDER_EMAIL message.to = the_email message.subject = _('Welcome to Gig-o-Matic') # message.body = u""" # Hello! You have registered to join Gig-o-Matic - click the link below to log in and you're good to go. (The link # is good for 48 hours - after that you can just register again to get a new one if you need it.) # # {0} # # Thanks, # The Gig-o-Matic Team # # """.format(the_url) message.body=_('welcome_msg_email').format(the_url) try: message.send() except: logging.error('failed to send email!') return True
def post(self): secret_code = self.request.get("secret") if secret_code != config.SECRET_CODE: self.response.out.write("fail1") return to_addr = self.request.get("to") from_addr = self.request.get("from") body = self.request.get("message") subject = self.request.get("subject") if not mail.is_email_valid(to_addr): # Return an error message... self.response.out.write("fail2") return message = mail.EmailMessage() message.sender = from_addr message.to = to_addr message.subject = subject message.body = body message.send() # self.response.out.write('success') template_values = {} path = os.path.join(os.path.dirname(__file__), "success.html") self.response.out.write(template.render(path, template_values))
def send_forgot_email(the_req, the_email, the_url): set_locale_for_user(the_req) if not mail.is_email_valid(the_email): logging.error("send_forgot_email invalid email: {0}".format(the_email)) return False message = mail.EmailMessage() message.sender = SENDER_EMAIL message.to = the_email message.subject = _('Gig-o-Matic Password Reset') # message.body = u""" # Hello! To reset your Gig-o-Matic password, click the link below. # # {0} # # Thanks, # The Gig-o-Matic Team # # """.format(the_url) message.body = _('forgot_password_email').format(the_url) try: message.send() except: logging.error('failed to send email!') return True
def send_sync(cls, to, sender, body, subject): """Syncronously sends a notification via email. Args: to: string. Recipient email address. Must have a valid form, but we cannot know that the address can actually be delivered to. sender: string. Email address of the sender of the notification. Must be a valid sender for the App Engine deployment at the time the deferred send_mail() call actually executes (meaning it cannot be the email address of the user currently in session, because the user will not be in session at call time). See https://developers.google.com/appengine/docs/python/mail/emailmessagefields. body: string. The data payload of the notification. Must fit in a datastore entity. subject: string. Subject line for the notification. Raises: ValueError: if to or sender are malformed according to App Engine (note that well-formed values do not guarantee success). """ for email in (to, sender): if not mail.is_email_valid(email): raise ValueError('Malformed email address: "%s"' % email) # Send the email try: send_html_email(sender, to, subject, body, None) except Exception, exception: # pylint: disable=broad-except logging.error('Failed to send email synchronously: %s', exception) return False
def post(self): nombre = self.request.get('nombre') apellido = self.request.get('apellido') email = self.request.get('email') user = self.request.get('user') pw = self.request.get('password') pw = SHA256.new(pw).hexdigest() #logging.info("pw:" + str(pw)) #fecha = self.request.get('fecha') sexo = self.request.get('sexo') if mail.is_email_valid(email): #Se crea uan entidad de tipos usuarios con propiedades estructuradas usuario=Usuario(nombre=nombre, apellido=apellido, email=email, sexo=sexo, cuenta=Cuentas(username=user,password=pw) ) #Se guarda la entidad de tipo usuario con propiedades estructuradas usuario=usuario.put() #Obtengo la llave de la entidad de usuario usuariokey=usuario.get() sender_address = "*****@*****.**" subject = "Registro completo" body = "Gracias por registrarse" mail.send_mail(sender_address,email, subject, body) self.redirect('/') else: self.render("registrar.html")
def email_booking_to_patient(handler, booking, activation_url=None): ''' send booking info to patient, provider and us ''' patient = booking.patient.get() provider = booking.provider.get() to_address = patient.email # check email valid if not mail.is_email_valid(to_address): logging.warn('Email is not valid: %s -- trying anyway...' % to_address) # create message message = mail.EmailMessage() message.sender = "Veosan" + ' <' + VEOSAN_SUPPORT_ADDRESS + '>' message.to = to_address category_label = dict(util.get_all_categories_all_domains())[provider.category] message.subject = '%s - %s' % (_(u'Veosan Appointment'), _(category_label).capitalize()) kw = {'booking': booking, 'activation_url': activation_url} logging.debug('activation url for email: %s' % activation_url) message.body = render_booking_email_body(handler.jinja2, 'email/patient_booking.txt', **kw) try: logging.info('Sending booking email to provider %s' % patient.email) message.send() booking.email_sent_to_patient = True booking.put() except Exception as e: logging.error('Email to patient not sent. %s' % e)
def Validate(data, typ, empty=False): if typ is ValidationTypes.String: if isinstance(data, unicode) == False: return False if empty is True: if data is None or len(data) == 0: return False elif typ is ValidationTypes.Integer: logging.info(data) if len(data) is 0: return False if isinstance(int(data), int) == False: return False if empty is True: if data is None: return False elif typ is ValidationTypes.Email: if mail.is_email_valid(data) == False: return False if empty is True: if data is None or len(data) == 0: return False elif typ is ValidationTypes.Array: if len(data) == 0: return False return True
def post(self): # user submitted an email message path = self.request.path temp = os.path.join(os.path.dirname(__file__), 'templates/contact.htm') theDict = {'path': path} name = self.request.get('name') theDict['name'] = name email = self.request.get('email') theDict['email'] = email message = self.request.get('message') theDict['message'] = message if not mail.is_email_valid(email) or '@' not in email: error = "The email address you entered does not appear to be valid." theDict['error'] = error del theDict['email'] elif len(name) == 0: theDict['error'] = "Please enter a name." elif len(message) == 0: theDict['error'] = "Please enter a message." if theDict.has_key('error'): outstr = template.render(temp, theDict) self.response.out.write(outstr) return sender = "*****@*****.**" to = "*****@*****.**" subject = "New Message posted to the C.J. Cubers website" message = "From: " + name + '\n' + "Email: " + email + '\n' + message mail.send_mail(sender, to, subject, message) theDict['greeting'] = "Your message has been sent, thank you!" outstr = template.render(temp, theDict) self.response.out.write(outstr)
def reply_notify(self): #reply comment mail notify if not self.blog.owner: return comment=self refers = re.findall(r'#comment-(\d+)', comment.content) if len(refers)!=0: replyIDs=[ndb.Key(Comment,int(a)) for a in refers] commentlist=ndb.get_multi(replyIDs) emaillist=[c.email for c in commentlist if c.reply_notify_mail] emaillist = {}.fromkeys(emaillist).keys() entry=comment.entry.get() for refer in emaillist: if mail.is_email_valid(refer): emailbody = BBODY%{'title':entry.title, 'author':comment.author, 'weburl':comment.weburl, 'email':comment.email, 'content':comment.content, 'commenturl':entry.fullurl+"#comment-"+str(comment.key.id()) } message = mail.EmailMessage(sender = self.blog.owner.email(),subject = 'Comments:'+entry.title) message.to = refer message.body = emailbody message.send()
def get(self): email_address = self.request.get("email_address") if not mail.is_email_valid(email_address): self.response.write('invalid email address') self.response.status = 400 return confirm_id = str(uuid.uuid4().get_hex().upper()[0:6]) confirmation_url = 'http://' + modules.get_hostname( ) + '/news/confirm?confirm_id=' + confirm_id subject = "Confirm your subscription" body = """Thank you for subscribing to splunk-sizing.appspot.com! Please confirm your email address by clicking on the link below: %s """ % confirmation_url subscription = Subscription.get_or_insert(email_address) if subscription.confirmed: self.response.write('already confirmed') self.response.status = 400 return subscription.confirm_date = None subscription.confirm_id = confirm_id subscription.put() mail.send_mail(sender_address, email_address, subject, body)