예제 #1
0
def add_source(request):
    if request.method == 'POST':
        form=ICalendarEditForm(request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, "Thanks for submitting an iCal!")
            if request.profile.userlevel < 10 :

                mail.send_mail(sender="Events bot ANGRY <*****@*****.**>",
                                            to="The Laziest Louts Ever <*****@*****.**>",
                                            #to="The Laziest Louts Ever <*****@*****.**>",
                                            subject="New Source Added, now get off your ass!",
                                            body="""
New Source! Needs Review: http://events.datacommunitydc.org/sources/manage/

The Angry Server.
                        """)
                return HttpResponseRedirect('/')
            else:
                return HttpResponseRedirect('/sources/manage/')

        else:
            return render_to_response('sources/add.html', locals(), context_instance=RequestContext(request))


    form=ICalendarEditForm()
    return render_to_response('sources/add.html', locals(), context_instance=RequestContext(request))
예제 #2
0
	def post(self):
		username = self.request.get('quotationrEmail')

		user = self.user_model.get_by_auth_id(username)
		if not user:
			logging.info('Could not find any user entry for username %s', username)
			self.response.out.write('fail:::cant find email')
			return

		user_id = user.get_id()
		token = self.user_model.create_signup_token(user_id)

		verification_url = self.uri_for('verification', type='p', user_id=user_id,
			signup_token=token, _full=True)

		
		logging.error(verification_url)
		
		mail.send_mail(sender="Quotationr <*****@*****.**>",
                to=user.email_address,
                subject="Reset Your Quotationr Password",
                body="Please click the following link to reset your Quotationr password:\n\n " + verification_url)
		
		#self.response.out.write('success:::' + user.email_address)
		self.response.out.write('success:::email sent')
예제 #3
0
    def sendRiderEmail(self, ride, to):

        if choice == "facebook":

            to = FBUser.get_by_key_name(to)
            logging.debug(to)
        sender = FROM_EMAIL_ADDR
        subject = "Change in your ride"

        body = """
Dear %s,

We wanted to let you know that there has been a change in status of your ride
from %s to %s on %s.  Unfortunately the driver is unable to drive anymore.
The ride will remain, but it will appear as a ride
that is in need of a driver.  When a new driver is found you will be notified
by email.


Sincerely,

The Rideshare Team
""" % (to.nickname(),  ride.start_point_title, ride.destination_title, ride.ToD)
        if choice != "facebook":
            mail.send_mail(sender,to.email(),subject,body)
        else:
            try:

                graph = facebook.GraphAPI(to.access_token)
                graph.put_object("me", "feed", message=body)

            except:
                logging.debug(graph.put_object("me", "feed", message=body))
예제 #4
0
    def send(self, to, subject='None', message='None',):
        """
        Sends an email. Returns True on success, False on failure.
        """

        if not isinstance(to, list):
            to = [to]
        try:
            if self.settings.server == 'gae':
                from google.appengine.api import mail
                mail.send_mail(sender=self.settings.sender, to=to,
                               subject=subject, body=message)
            else:
                msg = '''From: %s\r
To: %s\r
Subject: %s\r
\r
%s'''\
                     % (self.settings.sender, ', '.join(to), subject,
                        message)
                (host, port) = self.settings.server.split(':')
                server = smtplib.SMTP(host, port)
                justfortest=1
                if self.settings.login:
                    server.ehlo()
                    server.starttls()
                    server.ehlo()
                    (username, password) = self.settings.login.split(':')
                    server.login(username, password)
                server.sendmail(self.settings.sender, to, msg)
                server.quit()
        except Exception, e:
            return False
예제 #5
0
    def sendRiderEmail(self, ride, to):

        if choice == "facebook":
            to = FBUser.get_by_key_name(to)
            user = self.current_user
            logging.debug(to)
        sender = FROM_EMAIL_ADDR
        subject = "Change in your ride"

        body = """
Dear %s,

We have good news about your request for a ride from %s to %s on %s.
%s has agreed to drive.  You can contact the driver at %s.

Have a safe trip!

Sincerely,

The Rideshare Team
""" % (to.nickname(),  ride.start_point_title, ride.destination_title, ride.ToD,
       user.nickname(), ride.contact)
        if choice != "facebook":
            logging.debug(body)
            mail.send_mail(sender,to.email(),subject,body)
        else:
            graph = facebook.GraphAPI(to.access_token)
            graph.put_object("me", "feed", message=body)
예제 #6
0
  def  _QueueChangeTestPatternsAndEmail(
      self, entity, new_patterns, old_patterns):
    deferred.defer(
        _QueueChangeTestPatternsTasks, old_patterns, new_patterns)

    user_email = users.get_current_user().email()
    subject = 'Added or updated %s: %s by %s' % (
        self._model_class.__name__, entity.key.string_id(), user_email)
    email_key = entity.key.string_id()

    email_body = _NOTIFICATION_EMAIL_BODY % {
        'key': email_key,
        'new_test_path_patterns': json.dumps(
            list(new_patterns), indent=2, sort_keys=True,
            separators=(',', ': ')),
        'old_test_path_patterns': json.dumps(
            list(old_patterns), indent=2, sort_keys=True,
            separators=(',', ': ')),
        'hostname': app_identity.get_default_version_hostname(),
        'user': user_email,
    }
    mail.send_mail(
        sender=_SENDER_ADDRESS,
        to=_NOTIFICATION_ADDRESS,
        subject=subject,
        body=email_body)
예제 #7
0
파일: main.py 프로젝트: Yuffster/hd-signup
    def post(self, ids=None):
        subscriber_ids = self.request.get('subscriber_ids').split(',')
        c = Config()
        s = spreedly.Spreedly(c.SPREEDLY_ACCOUNT, token=c.SPREEDLY_APIKEY)
        for id in subscriber_ids:
            subscriber = s.subscriber_details(sub_id=int(id))
            logging.debug("customer_id: "+ subscriber['customer-id'])
            member = Membership.get_by_id(int(subscriber['customer-id']))
            if member:
                if member.status == 'paypal':
                    mail.send_mail(sender=EMAIL_FROM,
                        to=PAYPAL_EMAIL,
                        subject="Please cancel PayPal subscription for %s" % member.full_name(),
                        body=member.email)
                member.status = 'active' if subscriber['active'] == 'true' else 'suspended'
                if member.status == 'active' and not member.username:
                    taskqueue.add(url='/tasks/create_user', method='POST', params={'hash': member.hash}, countdown=3)
                if member.status == 'active' and member.unsubscribe_reason:
                    member.unsubscribe_reason = None
                member.spreedly_token = subscriber['token']
                member.plan = subscriber['feature-level'] or member.plan
                if not subscriber['email']:
                  subscriber['email'] = "*****@*****.**"
                member.email = subscriber['email']                
                member.put()
                # TODO: After a few months (now() = 06.13.2011), only suspend/restore if status CHANGED
                # As of right now, we can't trust previous status, so lets take action on each call to /update
                if member.status == 'active' and member.username:
                    logging.info("Restoring User: "******"Suspending User: "******"ok")
예제 #8
0
    def sendDriverEmail(self,ride):

        if not ride.driver:
            return
        if choice != "facebook":
            to = ride.driver.email()
        else:
            logging.debug(ride.driver)
            to = FBUser.get_by_key_name(ride.driver)
            logging.debug(to)
        sender = FROM_EMAIL_ADDR
        subject = "New Passenger for your ride"
        p = db.get(ride.passengers[-1])
        user = FBUser.get_by_key_name(p.name)
        body = """
Dear %s,
We wanted to let you know that %s has been added to your ride
from %s to %s on %s.  If you need to contact %s you can do so at %s.

Thanks for being a driver!

Sincerely,

The Rideshare Team
""" % (to.nickname(), user.nickname(), ride.start_point_title, ride.destination_title,
       ride.ToD, user.nickname(), p.contact)

        if choice != "facebook":
            logging.debug(body)
            mail.send_mail(sender,to,subject,body)
        else:
            graph = facebook.GraphAPI(to.access_token)
            logging.debug(graph)
            graph.put_object("me", "feed", message=body)
예제 #9
0
def send_contact_mail(self):
    contacts = Contact.query(Contact.sent != True)
    count = contacts.count()
    if count:
        datetime_handler = lambda obj: obj.isoformat() \
            if isinstance(obj, datetime) else None
        message = json.dumps(
            [contact.to_dict() for contact in contacts],
            default=datetime_handler,
            indent=4
        )

        mail.send_mail(
            sender="Getmewrite.com Support <*****@*****.**>",
            to="Mona <*****@*****.**>",
            subject="You have {0} new contact(s)".format(count),
            body=message
        )

        self.response.write(message)
        logger.info(
            'Send daily mail success, {0} new contacts'.format(count))

        put_list = []
        for contact in contacts:
            contact.sent = True
            put_list.append(contact)

        ndb.put_multi(put_list)
    def post(self):
        self.verify_permissions()
        suggestion_id = int(self.request.get("suggestion_id"))
        verdict = self.request.get("verdict")
        message = self.request.get("user_message")

        admin_email_body = None
        email_body = None
        user = None
        event_key = None
        status = ''
        if verdict == "accept":
            status = 'accept'
            auth_id, user, event_key, email_body = self._process_accepted(suggestion_id, message)
            admin_email_body = """{} ({}) has accepted the request with the following message:
{}

View the key: https://www.thebluealliance.com/admin/api_auth/edit/{}

""".format(self.user_bundle.account.display_name, self.user_bundle.account.email, message, auth_id)

        elif verdict == "reject":
            suggestion = Suggestion.get_by_id(suggestion_id)
            event_key = suggestion.contents['event_key']
            user = suggestion.author.get()
            event = Event.get_by_id(event_key)
            suggestion.review_state = Suggestion.REVIEW_REJECTED
            suggestion.reviewer = self.user_bundle.account.key
            suggestion.reviewed_at = datetime.now()
            suggestion.put()

            status = 'reject'
            email_body = """Hi {},

We have reviewer your request for auth tokens for {} {} and have regretfully declined with the following message:

{}

If you have any questions, please don't hesitate to reach out to us at [email protected]

Thanks,
TBA Admins
""".format(user.display_name, event.year, event.name, message)

            admin_email_body = """{} ({}) has rejected this request with the following reason:
{}
""".format(self.user_bundle.account.display_name, self.user_bundle.account.email, message)

        # Notify the user their keys are available
        if email_body:
            mail.send_mail(sender="The Blue Alliance Contact <*****@*****.**>",
                           to=user.email,
                           subject="The Blue Alliance Auth Tokens for {}".format(event_key),
                           body=email_body)
        if admin_email_body:
            # Subject should match the one in suggest_apiwrite_controller
            subject = "Trusted API Key Request for {}".format(event_key)
            SuggestionNotifier.send_admin_alert_email(subject, admin_email_body)

        self.redirect("/suggest/apiwrite/review?success={}".format(status))
예제 #11
0
파일: blog.py 프로젝트: goldinitp/goldi-io
 def send_email(self, emailTo, emailSubject, emailBody):
     """method to send mail"""
     mail.send_mail(sender=config.admin['admin_mail'],
                    to=emailTo,
                    subject=emailSubject,
                    body=emailBody)
     return
예제 #12
0
    def welcomeUser(cls,user):
        subject = "Welcome to eBenta!"
        body = """
Hi %(full_name)s!

Welcome to eBenta.com.ph! Our goal here at eBenta is to provide you (and other scholars) a platform where you could purchase and consign(sell) books. We are also planning to expand our services to other academic materials such as readings. As of now we offer the following services:

Purchasing of used or second hand quality books:
    Purchase books previously used and owned by scholars like yourself, at LOWER prices! Save up to 50%% on you book allowance!!
    Items will be checked by us to ensure quality and your satisfaction.

Purchasing of Brand New Books:
    If you prefer to purchase new books than used ones, well why not? Just request for a brand new copy on the books information page.

Consigning of used books:
    If you are not familiar with the word, consigning is very much like selling, but better. The formal definition of consigning is placing any material in the hand of another, but retaining ownership until the goods are sold or person is transferred. In other words, eBenta.com.ph sells your books for you! Hassle free isn't it?

    How consignment works:
        1. Search for the book you would like to consign, or
        2. Fill-up the request to consign form in ebenta.com.ph/consign.
        3. Wait for an administrator to contact you regarding your request.
        4. Agree on a price you would like your book to be sold.
        5. Wait for your book to be sold.
        6. Once your book has been sold, you will be notified thru email and/or SMS.
        7. Get your profit from eBenta.com.ph. Yay!!
    Note: You may withdraw your consigned item from us anytime.

This is an autogenerated message. You may reply to this email address to contact our administrators.
""" %{"full_name":user.completeName().strip()}
        mail.send_mail(sender,user.email,subject,body)
예제 #13
0
    def email(self):
        members = self.tournamentmatchupmembership_set.fetch(2)
        assert len(members) == 2

        tournament = self.parent()
        teams = [m.membership.team for m in members]
        for i in range(2):
            team = teams[i]
            opponent = teams[i ^ 1]

            mail.send_mail(
                sender="*****@*****.**",
                to=team.coach.user.email(),
                bcc="*****@*****.**",
                subject="OFTL tournament '%s' match-up notification!" % tournament.key().name(),
                body="""
Your %s %s tournament match with team %s is now scheduled against %s's %s. 
Please contact %s in the OFL/OFTL forums to arrange your match.
          """
                % (
                    tournament.key().name(),
                    self.get_round_name().lower(),
                    team.key().name(),
                    opponent.coach.key().name(),
                    opponent.key().name(),
                    opponent.coach.key().name(),
                ),
            )
예제 #14
0
    def get(self):

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'

        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            return self.redirect(users.create_login_url(self.request.uri))

        locations = OwnerLocations.all().filter('owner = ', users.get_current_user())

        user=users.get_current_user()
        if locations.count() == 0:
            locations = {}

        message_body = """
          Welcome to the miingle app
        """
        mail.send_mail(
              sender='*****@*****.**',
              to='*****@*****.**',
              subject='welcome to miingle',
              body=message_body)

        template_values = {
            'locations': locations,
            'userdisplay' : user.nickname(),
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'searchlocations.html')
        self.response.out.write(template.render(path, template_values))
예제 #15
0
파일: app.py 프로젝트: marlene15/proyecto
    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")    
예제 #16
0
def new_smiley():
    """ Input info for new user """
    in_use = []
    people = PeopleModel.all()
    for person in people:
        in_use.append(person.name)
    reservered = [u'new', u'debug', u'debug-people', u'home', u'about']

    form = PeopleForm()
    if form.validate_on_submit():
        person = PeopleModel(
                key_name = form.name.data.lower(),
                name = form.name.data.lower(),
                startdate = form.startdate.data,
                enddate = form.enddate.data,
                password = generate_password_hash(form.password.data)
                )
        person.name = slugify(person.name)
        if form.password.data == "":
            person.password = ""
        if unicode(person.name) not in in_use and (unicode(person.name) not in reservered):
                try:
                        person.put()
                        flash(unicode(person.name), 'success')
                        mail.send_mail(sender="Neuer Nutzer! <*****@*****.**>",\
                                to = "<*****@*****.**>", subject="Neuer Benutzer!", body=person.name)
                        return redirect(url_for('home') + person.name.encode("utf-8"))
                except CapabilityDisabledError:
                        flash(u'App Engine Datastore is currently in read-only mode.', 'failure')
                        return redirect(url_for('list_examples'))
        else:
            flash(u'Der Name ist leider schon reserviert, probiere doch einfach einen anderen')
            return redirect(url_for('new_smiley'))
    return render_template('setup.html', form=form)
def send(senderName, senderEmail, body):
    mail.send_mail(sender = 'www.martinadlerphotography.com <*****@*****.**>',
              to = '*****@*****.**',
              subject = 'From ' + senderName,
              body = 'Email: ' + senderEmail + '\n\n' + body)

    return { 'status' : 1, 'message' : 'Message sent' }
예제 #18
0
파일: tasks.py 프로젝트: saga/kindledump
def send(request):
    ready_data_key = request.POST.get('ready_data_key', None)

    if ready_data_key is None:
        logging.error('missing parameter')
        raise TypeError('missing parameter')

    ready_data = ReadyData.get(ready_data_key)
    if ready_data is None:
        logging.error('ReadyData object not found: %s', ready_data_key)
        raise TypeError('ReadyData object not found')

    user = ready_data.owner
    conf = UserConf.gql("WHERE user = :1", user).get()

    sender = "kindledump.appspot.com <*****@*****.**>" % conf.username()
    #to_addr = conf.kindle_mail
    to_addr = user.email()
    subject = "Convert"
    message = "(%s) %s" % (ready_data.merged, ready_data.created)
    attachments = [
        ('kindledump_articles.html', str(ready_data.as_html_page())),
    ]
    mail.send_mail(sender=sender, to=to_addr, subject=subject, body=message,
            attachments=attachments)

    # we won't need it anymore
    ready_data.delete()

    return True
예제 #19
0
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    #Form data
    book_id = cgi.escape(self.request.get("book_id"))
    book = models.Book.get(book_id)

    # if the book is valid, update it.
    if(book):
      mail.send_mail(sender="RPI QuickSell <*****@*****.**>",
                     to=book.user.email(),
                     subject=user.nickname() + " wants to purchase " + book.unique.title,
                     reply_to=user.email(),
                     body="""
      Hello:

      Your book, %s, has a potential buyer.  Please email them at: %s.

      The Quick Sell Team
      """ % (book.unique.title, user.email()))
    
    url_to_go = "/bookInformation?id=%s&e=1" % (book_id)
    logging.debug(str(book_id) + ", " + url_to_go)
    self.redirect(url_to_go)
예제 #20
0
 def SendToKindle(self, emails, title, booktype, attachment, tz=TIMEZONE, filewithtime=True):
     if not isinstance(emails, list):
         emails = [emails,]
         
     if PINYIN_FILENAME: # 将中文文件名转换为拼音
         from calibre.ebooks.unihandecode.unidecoder import Unidecoder
         decoder = Unidecoder()
         basename = decoder.decode(title)
     else:
         basename = title
     
     for email in emails:
         user = KeUser.all().filter("kindle_email = ", email).get()
         tz = user.timezone if user else TIMEZONE
         if filewithtime:
             filename = "%s(%s).%s"%(basename,local_time('%Y-%m-%d_%H-%M',tz=tz),booktype)
         else:
             filename = "%s.%s"%(basename,booktype)
         try:
             mail.send_mail(SrcEmail, email, "KindleEar", "Deliver from KindlerEar",
                 attachments=[(filename, attachment),])
         except OverQuotaError as e:
             self.log.warn('overquota when sendmail to %s:%s', (email, str(e)))
             self.deliverlog(email, title, len(attachment), tz=tz, status='over quota')
         except Exception as e:
             default_log.warn('sendmail to %s failed:%s', (email, str(e)))
             self.deliverlog(email, title, len(attachment), tz=tz, status='send failed')
         else:
             self.deliverlog(email, title, len(attachment), tz=tz)
예제 #21
0
파일: main.py 프로젝트: artxgj/hd-signup
 def post(self, hash):
     username = self.request.get('username')
     password = self.request.get('password')
     if password != self.request.get('password_confirm'):
         self.redirect(self.request.path + "?message=Passwords don't match")
     elif len(password) < 6:
         self.redirect(self.request.path + "?message=Password must be 6 characters or longer")
     else:
         m = Membership.all().filter('hash =', hash).get()
         
         if m and m.spreedly_token:
             try:
                 resp = urlfetch.fetch('http://domain.hackerdojo.com/users', method='POST', payload=urllib.urlencode({
                     'username': username,
                     'password': password,
                     'first_name': m.first_name,
                     'last_name': m.last_name,
                     'secret': keymaster.get('*****@*****.**'),
                 }), deadline=10)
                 out = resp.content
             except urlfetch.DownloadError, e:
                 out = str(e)
         
         usernames = fetch_usernames(False)
         if username in usernames:
             m.username = username
             m.put()
             self.redirect('/success/%s?email' % hash)
         else:
             mail.send_mail(sender=EMAIL_FROM,
                 to="Jeff Lindsay <*****@*****.**>",
                 subject="Error creating account for %s" % username,
                 body=out if m.spreedly_token else "Attempt to make user without paying: " + self.request.remote_addr)
             self.redirect(self.request.path + "?message=There was a problem creating your account. Please contact an admin.")
예제 #22
0
파일: main.py 프로젝트: jackyueq/KindleEar
    def SendToKindle(self, name, to, title, booktype, attachment, tz=TIMEZONE, filewithtime=True):
        if PINYIN_FILENAME:  # 将中文文件名转换为拼音
            from calibre.ebooks.unihandecode.unidecoder import Unidecoder

            decoder = Unidecoder()
            basename = decoder.decode(title)
        else:
            basename = title

        lctime = local_time("%Y-%m-%d_%H-%M", tz)
        if filewithtime:
            filename = "%s(%s).%s" % (basename, lctime, booktype)
        else:
            filename = "%s.%s" % (basename, booktype)
        try:
            mail.send_mail(
                SrcEmail, to, "KindleEar %s" % lctime, "Deliver from KindlerEar", attachments=[(filename, attachment)]
            )
        except OverQuotaError as e:
            default_log.warn("overquota when sendmail to %s:%s" % (to, str(e)))
            self.deliverlog(name, to, title, len(attachment), tz=tz, status="over quota")
        except Exception as e:
            default_log.warn("sendmail to %s failed:%s" % (to, str(e)))
            self.deliverlog(name, to, title, len(attachment), tz=tz, status="send failed")
        else:
            self.deliverlog(name, to, title, len(attachment), tz=tz)
예제 #23
0
def send_email(content, status_code, reminder):
    if reminder:
        subj = "REMINDER: Infinispan.org is STILL down!!"
    else:
        subj = "Infinispan.org seems to be down!!"

    attach_txt = ""
    attachments = []
    if status_code == 200:
        attach_txt = "\nEven though this is a valid response code, errors were detected in what was rendered. Please inspect the attached file."
        attachments.append(("page_we_saw.html", content))

    nag = ""
    if reminder:
        nag = "*** A gentle prod to remind you ***\n"
    txt = """
Dear human:

%sThis script has detected that http://www.infinispan.org is down and currently returns HTTP response code %s.%s

Please fix this ASAP!

Best regards,
The Infinispan.org monitoring automaton""" % (nag, status_code, attach_txt)

    logging.info("Sending email!")
#    logging.debug("Subject %s and contents %s" % (subj, txt))
    if attachments:
        mail.send_mail(sender="Infinispan Website Monitor <*****@*****.**>",
                  to="Mark Newton <*****@*****.**>",
                  subject=subj, body=txt, cc = "Manik Surtani <*****@*****.**>", attachments = attachments)
    else:
        mail.send_mail(sender="Infinispan Website Monitor <*****@*****.**>",
                  to="Mark Newton <*****@*****.**>",
                  subject=subj, body=txt, cc = "Manik Surtani <*****@*****.**>")
예제 #24
0
def email_me(**kwargs):
  """Thin wrapper around mail.send_mail() that handles errors."""
  try:
    mail.send_mail(sender='*****@*****.**',
                   to='*****@*****.**', **kwargs)
  except BaseException:
    logging.exception('Error sending notification email')
예제 #25
0
 def authenticate(self, mail_message):
     auth_url = gdata.gauth.generate_auth_sub_url('https://mc-towel.appspot.com/auth', 'http://www.google.com/calendar/feeds/', secure=False, session=True, domain='mindcandy.com')
     logging.debug("Generated auth_url " + str(auth_url))
     mail.send_mail(sender=mail_message.to,
                     to=mail_message.sender,
                     subject="Re: %s" % mail_message.subject,
                     body="ERROR: Please visit this url for authorization:\n %s" % auth_url)
예제 #26
0
파일: main.py 프로젝트: bluehat/hd-signin
 def get(self):
   staff_members = db.GqlQuery("SELECT * FROM Signin WHERE created >= DATETIME(:start) AND type IN :types ",
     start=(datetime.now(Pacific())-timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S"),types=['StaffKey','StaffNoKey'])
   content = """To Dojo Members:\n\nThanks for helping run the dojo last week!  Our heros included:\n\n""" % locals()
   totals = {}
   emails = []
   for staff_member in staff_members:
     staff_member.name = string.capwords(staff_member.name)
     if staff_member.time_delta:
       emails.append(staff_member.email)
       if staff_member.time_delta > MAX_SIGNIN_TIME:
         staff_member.time_delta = MAX_SIGNIN_TIME
       if staff_member.name in totals.keys():
         totals[staff_member.name] = totals[staff_member.name]+staff_member.time_delta
       else:
         totals[staff_member.name] = staff_member.time_delta
   for total in sorted(totals.keys()):
     if(totals[total] > 0):
       content = content + " - " + total + ": " + str(math.floor(float(totals[total])/360)/10 ) + " hours\n"
     else:
       pass
   content = content + """\nThanks,\nEveryone at the Dojo"""
   if self.request.get('sendemail'):
     weekof = (datetime.now(Pacific())-timedelta(days=7)).strftime("%b %e")
     mail.send_mail(sender="Signin Machine <*****@*****.**>",
                 to="*****@*****.**",
                 subject="Hacker Dojo Member Appreciation - Week of " + weekof,
                 body=content)
   self.response.out.write(content)
예제 #27
0
 def __send_mail(self, content, receiver, subject):
     mail.send_mail(sender="*****@*****.**",
                    to=receiver,
                    subject=subject,
                    body='',
                    html=content)
     logging.info('Mail result for magicformula to %s' % (receiver))
예제 #28
0
파일: gobuild.py 프로젝트: jnwhiteh/go
def notifyBroken(c, builder):
    def send():
        n = Commit.get(c.key())
        if n is None:
            logging.error("couldn't retrieve Commit '%s'" % c.key())
            return False
        if n.fail_notification_sent:
            return False
        n.fail_notification_sent = True
        return n.put()
    if not db.run_in_transaction(send):
	return

    subject = const.mail_fail_subject % (builder, c.desc.split('\n')[0])
    path = os.path.join(os.path.dirname(__file__), 'fail-notify.txt')
    body = template.render(path, {
        "builder": builder,
        "node": c.node,
        "user": c.user,
        "desc": c.desc,
        "loghash": logHash(c, builder)
    })
    mail.send_mail(
        sender=const.mail_from,
        to=const.mail_fail_to,
        subject=subject,
        body=body
    )
예제 #29
0
    def get(self):
        """Send a reminder email to each User with an email who has
        games in progress. Email body includes a count of active games and their
        urlsafe keys
        Called every 12 hours using a cron job"""
        users = User.query(User.email != None)

        for user in users:
            games = Game.query(ndb.OR(Game.user_1 == user.key,
                                      Game.user_2 == user.key)). \
                filter(Game.game_over == False)
            if games.count() > 0:
                subject = 'This is a reminder!'
                body = 'Hello {}, you have {} games in progress. Their' \
                       ' keys are: {}'. \
                    format(user.name,
                           games.count(),
                           ', '.join(game.key.urlsafe() for game in games))
                logging.debug(body)
                # This will send test emails, the arguments to send_mail are:
                # from, to, subject, body
                mail.send_mail('noreply@{}.appspotmail.com'.
                               format(app_identity.get_application_id()),
                               user.email,
                               subject,
                               body)
예제 #30
0
def feedback():
  if not config.CONFIG_DB.feedback_email:
    return flask.abort(418)

  form = FeedbackForm()
  if form.validate_on_submit():
    mail.send_mail(
        sender=config.CONFIG_DB.feedback_email,
        to=config.CONFIG_DB.feedback_email,
        subject='[%s] %s' % (
            config.CONFIG_DB.brand_name,
            form.subject.data,
          ),
        reply_to=form.email.data or config.CONFIG_DB.feedback_email,
        body='%s\n\n%s' % (form.message.data, form.email.data)
      )
    flask.flash('Thank you for your feedback!', category='success')
    return flask.redirect(flask.url_for('welcome'))
  if not form.errors and auth.current_user_id() > 0:
    form.email.data = auth.current_user_db().email

  return flask.render_template(
      'feedback.html',
      title='Feedback',
      html_class='feedback',
      form=form,
    )
예제 #31
0
def mail_sender(request, *args, **kwargs):

    if request.method != "POST":
        return ""

    message = ""
    for k, v in request.POST.iteritems():
        message += "%s: %s\n" % (k, v)
    message += "ip address: %s\n" % str(request.remote_addr)

    if kwargs["id"] == "relational":
        from google.appengine.api import mail

        mail.send_mail(
            sender="Feedback service <*****@*****.**>",
            to="*****@*****.**",
            subject="Feedback from %s" % kwargs["id"],
            body=message)

    return "Message queued"
예제 #32
0
    def _send_mail(self, email):
        # TODO(csilvers): make this a template instead.
        body = """\
Just a reminder that weekly snippets are due at 5pm today!  Our
records show you have not yet entered snippet information for last
week.  To do so, visit
   http://weekly-snippets.appspot.com/

If you'd like to stop getting these reminder emails, visit
   http://weekly-snippets.appspot.com/settings
and click 'no' under 'Receive reminder emails'.

Regards,
your friendly neighborhood snippet server
"""
        mail.send_mail(sender=('Khan Academy Snippet Server'
                               ' <*****@*****.**>'),
                       to=email,
                       subject='Weekly snippets due today at 5pm',
                       body=body)
예제 #33
0
 def post(self):
  sender = self.request.get("sender")
  recipient = self.request.get("recipient")
  message = self.request.get("message")
  notify = self.request.get("notify") == "1"
  xmpp.send_invite(recipient)
  if can_converse(recipient) and len(message) > 0:
   xmpp.send_message(recipient, message)
  else:
   if notify:
    xmpp.send_message(recipient, "This is an automated message. Do not reply.")
   if len(message) > 0:
    add_message(get_nickname(recipient), get_nickname(sender), message)
  if notify:
   mail.send_mail(NO_REPLY_EMAIL,
                  recipient,
                  "Automated Message - Do Not Reply",
                  "This is an automated message. Do not reply.")
  if not IS_PRODUCTION:
   self.response.out.write(unicode(message + get_messages(get_nickname(recipient))))
예제 #34
0
def _SendNotificationEmail(old_test_key, new_test_key):
  """Send a notification email about the test migration.

  This function should be called after we have already found out that there are
  no new rows to move from the old test to the new test, but before we actually
  delete the old test.

  Args:
    old_test_key: TestMetadata key of the test that's about to be deleted.
    new_test_key: TestMetadata key of the test that's replacing the old one.
  """
  body = _SHERIFF_ALERT_EMAIL_BODY % {
      'old_test_path': utils.TestPath(old_test_key),
      'new_test_path': utils.TestPath(new_test_key),
  }
  mail.send_mail(
      sender='*****@*****.**',
      to='*****@*****.**',
      subject='Sheriffed Test Migrated',
      body=body)
예제 #35
0
파일: views.py 프로젝트: asplabs/MyProfile
    def post(self, request, *args, **kwargs):
        mail.send_mail(
            sender="%s <%s>" % (request.POST.get('your-name'), request.POST.get('your-email')),
            to="Arun Shanker Prasad <*****@*****.**>",
            subject="%s has sent you a message from your profile website" % request.POST.get('your-name'),
            body="""
Dear Arun,

Company: %s

Website: %s

The message:

%s

Your Profile.
""" % (request.POST.get('company'), request.POST.get('website'), request.POST.get('message')))

        return HttpResponseRedirect(reverse('home'))
예제 #36
0
 def get(self):                  
     env = GenFromGrammar.GenEnvFromFile(GRAMMAR_FILE_NAME)
     # stmt, id = GenFromGrammar.GenerateSentence(env)    
     stmt, stmtId, tips, tipsId, combinedId = GenFromGrammar.GenerateSentenceWithTipsAndIDs(env)
     thisStmtLink = os.path.join(os.path.split(self.request.url)[0], UrlForId(combinedId))        
     mySender = "Prashnayantra <*****@*****.**>"
     myTo = "*****@*****.**"
     mySubject = "[Test] Prashnayantra Problem Statement for {0}".format(datetime.date.today().strftime("%d %b %Y"))
     myBody = EMAIL_BODY_TEXT.format(stmt, GetThoughtsForTextList(tips), stmtId, GetHintsIdForHtml(tipsId), thisStmtLink)
     myHtml = EMAIL_BODY_HTML.format(stmt, GetThoughtsForHtmlList(tips), stmtId, GetHintsIdForHtml(tipsId), thisStmtLink)
     try:
         mail.send_mail(sender=mySender,
                        to=myTo,
                        subject=mySubject,
                        body=myBody,
                        html=myHtml)
         self.response.headers['Content-Type'] = 'text/plain'
         self.response.write("Sent email:\n" + myBody)        
     except:
         self.response.write("Exception. " + sys.exc_info()[0])
    def get(self):
        """
        Send a reminder email to each User about each unfinished game.
        Called every hour using a cron job
        """

        games = ConcentrationGameApi._get_reminder_games()
        app_id = app_identity.get_application_id()
        for game in games:
            user = game.user.get()
            if user.email:
                subject = 'You have not made a move in a game in over 12 hours'
                body = 'Hello {}, try out Guess A Number!' \
                    .format(user.username)
                mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                               user.email, subject, body)

            # Avoid repeatedly sending emails
            game.email_sent = True
            game.put()
예제 #38
0
    def send_info_email(cls, construction, pos_b, a):
        query = PendingBlockEmail.all().ancestor(construction)
        pending_block_email = query.get()
        if pending_block_email is None:
            raise Exception('Could not get pending block email data')

        sender_address = pending_block_email.sender_address
        recipient_address = pending_block_email.recipient_address
        subject = "New Pending Block"
        body = """
Position: %d, %d, %d
Angle: %d
""" % (pos_b[0], pos_b[1], pos_b[2], a)

        try:
            mail.send_mail(sender_address, recipient_address, subject, body)
        except:
            return False

        return True
예제 #39
0
def forgotpassword():
    mailid = request.form['mail']
    uid = str(uuid.uuid4())
    utc = pytz.UTC
    timestamp = datetime.now().replace(tzinfo=utc)
    timestamp = timestamp.time()
    sender = str("*****@*****.**")
    confirmation = ForgotPassword(id=mailid,
                                  email=mailid,
                                  uid=uid,
                                  timestamp=timestamp)
    confirmation.put()
    subject = str('Reset Password - link')
    link = 'https://workwithflask.appspot.com/resetpassword/{}&id={}'.format(
        uid, mailid)
    mail.send_mail(sender, mailid, subject, link)
    flash(
        'Reset Password Link has been sent to your Email,Please check within 10 mins'
    )
    return redirect(url_for('homepage'))
예제 #40
0
    def sendconfirmationmail(email_to, token):
        link = 'http://' + BasicUtils.get_production_domain(
        ) + '/register?token=' + token + '&mail=' + email_to
        body_field = """

Thank you for registering at FableMe.com

We have successfully received your membership registration and your personal profile has been created. 

In order to to activate your account you must verify your email address. 
Click here to verify your account: 
{{link}}
        
        """
        logging.debug('Mail link: ' + link)
        mail.send_mail(
            sender="FableMe.com Support <*****@*****.**>",
            to=email_to,
            subject="FableMe.com - Registration confirmation",
            body=body_field.replace('{{link}}', link))
def _SendStoppageAlertEmail(sheriff_entity):
  """Sends a summary email for the given sheriff rotation.

  Args:
    sheriff_entity: A Sheriff key.
  """
  stoppage_alerts = _RecentStoppageAlerts(sheriff_entity)
  if not stoppage_alerts:
    return
  alert_dicts = [_AlertRowDict(a) for a in stoppage_alerts]
  test_owners = _TestOwners(stoppage_alerts)
  mail.send_mail(
      sender='*****@*****.**',
      to=email_template.GetSheriffEmails(sheriff_entity),
      subject=_Subject(sheriff_entity, stoppage_alerts),
      body=_TextBody(alert_dicts, test_owners),
      html=_HtmlBody(alert_dicts, test_owners))
  for alert in stoppage_alerts:
    alert.mail_sent = True
  ndb.put_multi(stoppage_alerts)
예제 #42
0
    def get(self):
        url = self.request.get("urls")

        url = url.replace("((((()))))", "#")
        urls = url.split(",")

        URLs = models.Links(URLs=urls)
        URLs.put()
        self.response.write(str(URLs.key()))
        user_address = self.request.get("email")
        urltosend = "tabbybackend.appspot.com/linkhandler?key=" + str(
            URLs.key())
        sender_address = "<Tabby> [email protected]"
        subject = "Someone special you some tabs"
        body = """
Click here to see your special surprise:

%s
""" % urltosend
        mail.send_mail(sender_address, user_address, subject, body)
예제 #43
0
    def get(self):
        userToActivate = str(self.request.GET['email'])
        user = users.get_current_user().email()
        logout_url = users.create_logout_url(dest_url=self.request.host_url)
        params = { 'email' : userToActivate, 'logout' : logout_url }
        if user == ADMIN:
            record = db.Query( AllowedUser ).filter('email', userToActivate).fetch(1,0)[0]
            record.status = ACTIVE
            record.put() # errori non gestisti
            html = VisitorActivatedTemplate( params ).render()
            mail.send_mail(
                sender=ADMIN,
                to=userToActivate,
                subject="Sei stato attivato",
                body="Ora hai accesso alla risorsa" )

            logging.info("Email di notifica inviata")
        else:
            html = VisitorActivatedErrorTemplate(params).render()
        return self.response.write(html)
예제 #44
0
    def get(self):
        subscribers = User.query(User.forum_subscription == True).fetch()

        latest_topics = Topic.query(
            Topic.deleted == False, Topic.updated >
            datetime.datetime.now() - datetime.timedelta(days=1)).fetch()

        if latest_topics:
            topic_link = ""
            for topic in latest_topics:

                topic_link += topic.title + "- " + "http://wd2-forum-tilen.appspot.com/topic/" + str(
                    topic.key.id()) + " , "

            for subscriber in subscribers:
                mail.send_mail(
                    sender="*****@*****.**",
                    to=subscriber.email,
                    subject="Here are the latest topics from our forum!",
                    body="Topics: %s" % topic_link)
예제 #45
0
    def sendforgotpassword(self, password):
        body_field = """

Your account's password at FableMe.com has been reset.

Your new password is:
{{pwd}}

You are suggested to change your password at your next logon, by selecting
'My FableMe / My Account' from the top bar menu.

See you soon at
http://www.fableme.com

        """
        mail.send_mail(
            sender="FableMe.com Support <*****@*****.**>",
            to=self.email_address,
            subject="FableMe.com - Password Reset",
            body=body_field.replace('{{pwd}}', password))
예제 #46
0
파일: api.py 프로젝트: johan--/gfw-api
    def _send_new_story_emails(self):
        story = self._get_params()

        # Email WRI:
        subject = 'A new story has been registered with Global Forest Watch'
        sender = \
            'Global Forest Watch Stories <*****@*****.**>'
        to = runtime_config.get('wri_emails_stories')
        story_url = 'http://globalforestwatch.org/stories/%s' % story['id']
        api_url = '%s/stories/%s' % (common.APP_BASE_URL, story['id'])
        token = story['token']
        body = 'Story URL: %s\nStory API: %s\nStory token: %s' % \
            (story_url, api_url, token)
        mail.send_mail(sender=sender, to=to, subject=subject, body=body)

        # Email user:
        subject = 'Your story has been registered with Global Forest Watch!'
        to = '%s <%s>' % (story['name'], story['email'])
        body = 'Here is your story: %s' % story_url
        mail.send_mail(sender=sender, to=to, subject=subject, body=body)
예제 #47
0
파일: main.py 프로젝트: saravgn/ticTacToe
 def get(self):
     """Reminder to users with incomplete games"""
     users = User.query(User.email != None)
     for user in users:
         games = Game.query(ndb.OR(Game.playerX == user.key,
                                   Game.playerO == user.key)). \
                         filter(Game.game_over == False)
         if games.count() > 0:
             subject = 'This is a reminder!'
             body = 'Hello {}, this email is for advice you about the '\
                    'games that are in progress. ' \
                    'You have {} games incompleted.' \
                    'The games keys are: {}'.format(user.name, games.count(),
                                               ', '.join(game.key.urlsafe() for game in games))
             # This will send test emails, the arguments to send_mail are:
             # from, to, subject, body
             mail.send_mail(
                 'noreply@{}.appspotmail.com'.format(
                     app_identity.get_application_id()), user.email,
                 subject, body)
예제 #48
0
    def send_email_to_coach(self):
        fromaddr = '*****@*****.**'
        toaddr = self.mailto

        self.convert_to_xls()

        # send email
        if not self.generate_goals_dashboard:
            subject = 'Khan Academy: Class report data in XLS format'
            body = "Hello %s,\n\nPlease find the class report you had requested, attached as an XLS file. If you have any questions or comments please contact [email protected]\n\nCheers!\nKhan Academy Implementation team" % self.coach.split(
                '@')[0]

            filename = "student_data.xls"
            mail.send_mail(sender=fromaddr,
                           to=toaddr,
                           subject=subject,
                           body=body,
                           attachments=[(filename,
                                         self.excel_output.getvalue())])

            self.excel_output.close()

        else:
            self.create_tgz()

            subject = 'Khan Academy: Goals dashboard data'
            body = "Hello %s,\n\nPlease find the goals dashboard data you had requested, attached as a tar/gzipped (tgz) file. Please follow the steps below to access the data.\n\n1. Save the archive (tgz file) in any directory\n2. Open and extract the two files in the archive\n3. First open the file named student_data.xls, then open the file named goals_dashboard.xls\n4. When you open goals_dashboard.xls, 'Enable Macros' and 'Update Links' (it might be 'Enable Content' and 'Update Content' on some versions of Excel) when asked\n5. Go to the 'Summary' sheet of the goals_dashboard.xls workbook and click on the Recalculate button\n6. You will see your students progress color coded on the 'Dashboard' sheet and the summary on the 'Summary' sheet.\n\nIf you have any questions or comments please contact [email protected]\n\nCheers!\nKhan Academy Implementation team\n\nPS: On Windows machines, if you don't have winzip, you might want to download a version of winzip (a free version may be downloaded from download.cnet.com)" % self.coach.split(
                '@')[0]

            filename = "goals_report.tgz"
            mail.send_mail(sender=fromaddr,
                           to=toaddr,
                           subject=subject,
                           body=body,
                           attachments=[(filename, self.tgz_output.getvalue())
                                        ])

            self.excel_output.close()
            self.tgz_output.close()

        return
예제 #49
0
def send_owner_message(flag, host):
    """
    Sends a message to the person responsible for flagged content.
    :param flag: any Flag
    :type flag: Flag
    :param host: the site host as a string
    """

    message = ("Hello Spudder User!\n" +
               "The page that you manage (http://%s%s) " % (host, flag.url) +
               "has been marked as containing %s content" % type +
               ". Please review the following fields:\n")

    if flag.custom_imgs:
        message += "\nCustom image"
        if len(flag.custom_imgs) > 1:
            message += "s"
        message += ":\n"

        image_links = flag.get_images_as_links()
        for key in image_links:
            message += "%s (visible at http://%s%s)\n" % (key, host,
                                                          image_links[key])

    if flag.custom_text:
        message += "\nCustom text field"
        if len(flag.custom_text) > 1:
            message += "s"
        message += ":\n"

        for key in flag.custom_text:
            message += "%s: %s\n" % (key, flag.custom_text[key])

    message += "\nThe flagger left you the following comment: \n%s" % flag.comment

    subject = "Your page has been flagged with %s content" % flag.flag_type

    mail.send_mail(subject=subject,
                   body=message,
                   sender=settings.SERVER_EMAIL,
                   to=[flag.owner.email])
예제 #50
0
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'

        logging.info("Checking consistency of repository names.")
        failed_repos = check_failed_repos()

        res = {
            'result': None
        }

        if len(failed_repos) > 0:
            res['failed_repos'] = failed_repos
            res['result'] = "error"
            logging.error("There were issues in the repository name matching.")

            error_message = "\n".join([", ".join(x) for x in failed_repos])
            mail.send_mail(
                sender=SENDER,
                to=ADMINS,
                subject="Resource name checker failed",
                body="""
Hey there,

This is an automatic message sent by the Resource name checker to inform
you that the script found {0} name inconsistencies in some repositories between
the Carto resource_staging table and the name of organization and/or repository
on GitHub. These are the specific repositories that failed (names as in
Carto):

{1}

Please, fix them and then go to {2} to restart the process.

Thank you!
""".format(len(failed_repos), error_message, "http://%s/" % MODULE_URL))

        else:
            res['result'] = "success"
            logging.info("The consistency check could not find any issue.")

        self.response.write(json.dumps(res))
예제 #51
0
    def post(self):
        email = self.request.get('email')
        mode = self.request.get('mode')

        if not re.search(r'^[1-6]$', mode):
            self.response.set_status(404)
            return

        error = ''
        if not email:
            error = 'メールアドレスを入力してください'
        elif (not mail.is_email_valid(email)) or (re.search(
                '^[^@]+@[^@]+$', email) is None):
            error = 'メールアドレスの形式をお確かめください'

        if error:
            params = {
                'mode': mode,
                'email': email,
                'error': error,
            }
            path = os.path.join(os.path.dirname(__file__), 'to.html')
            self.response.out.write(template.render(path, params))
            return

        sender = '*****@*****.**'
        subject = 'コソリップからこっそりとお知らせです'
        body = messages[mode]

        params = {
            'base_url': 'http://cosolip.appspot.com/',
            'mode': mode,
        }
        path = os.path.join(os.path.dirname(__file__), 'mail.html')
        # for debug in browser
        # self.response.out.write(template.render(path, params))
        # return
        html = template.render(path, params)
        mail.send_mail(sender, email, subject, body, html=html)

        self.redirect('/sent?mode=%s' % mode)
예제 #52
0
파일: auth_handlers.py 프로젝트: lite/deone
 def post(self):
     nickname = self.request.get('nickname')
     email = self.request.get('email')
     password = self.request.get('password')
     password2 = self.request.get('password2')
     if password2 != password:
         self.session.start(None)
         self.session['flash_msg'] = '<p>Password fields did not match.</p>'
         self.redirect('/signup')
         return
     user = User.get_or_insert(nickname=nickname,
                               email=email,
                               pwd=salt_n_hash(password),
                               key_name=nickname)
     self.session.start(None)
     if not User.authenticate(nickname, password):
         self.session[
             'flash_msg'] = '<p>Sorry, the nickname you chose is already taken.</p>'
         self.redirect(self.request.url)
         return
     id = signup_id(nickname)
     signup = UserSignup(user=user, key_name=id)
     signup.put()
     confirm_url = self.request.relative_url('confirmsignup?id=' + id)
     logging.info("user:"******" password:"******" confirm_url:" + confirm_url)
     from google.appengine.api import mail
     #sender = 'Registrar <*****@*****.**>'
     sender = '*****@*****.**'
     subject = 'Confirm your registration'
     body = \
         'Hello %s,\n\n' % nickname + \
         'To confirm your registration, please visit the link below:\n\n' + \
         '<%s>\n' % confirm_url
     mail.send_mail(sender, email, subject, body)
     self.session['flash_msg'] = \
         '<p>Thank you for signing up, %s! A confirmation ' % nickname + \
         'message is on its way to your email inbox. It will contain a link ' + \
         'which you will need to visit in order to complete your registration.</p>' + \
         '<p>See you soon!</p>'
     self.redirect('/')
예제 #53
0
파일: main.py 프로젝트: sophxia/cssi
    def post(self):
        t = time.time()
        num_people = int(self.request.get("num_people"))
        toppings = self.request.get("toppings")
        location = self.request.get("location")
        email = self.request.get("email")
        c = Customer(time=t,
                     num_people=num_people,
                     toppings=toppings,
                     location=location,
                     email=email)
        for temp in Customer.query().fetch():
            print c.time - temp.time
            if c.time - temp.time > 3600:

                mail.send_mail(sender="*****@*****.**",
                               to=temp.email,
                               subject="No Matches Found...",
                               body=env.get_template(
                                   'resources/noMatchTemp.txt').render())

                temp.key.delete()
            elif c.email == temp.email:
                temp.key.delete()
        for temp in Customer.query().fetch():
            if (
                    c.num_people + temp.num_people
            ) % 4 == 0 and c.toppings == temp.toppings and c.location == temp.location:
                print c.email
                print temp.email
                #
                self.send_mail(c.get_mail_info(temp))
                self.send_mail(temp.get_mail_info(c))

                # EmailHandler(c, temp);
                temp.key.delete()

                self.response.write(env.get_template('results.html').render())
                return
        c.put()
        self.response.write(env.get_template('results.html').render())
예제 #54
0
def notify_students():
    if current_user.user_type != 'admin':
        return 403

    students = []
    with open('application/COMP3702.txt') as theory_file:
        for email_address in theory_file.read().split(','):
            students.append(email_address)
            models.StudentCourse(email_address=email_address,
                                 courses=['COMP3702']).put()

    with open('application/COMP3161.txt') as db_file:
        for email_address in db_file.read().split(','):
            students.append(email_address)
            student_course = models.StudentCourse.query().filter(
                models.StudentCourse.email_address == email_address).get()
            if student_course is None:
                models.StudentCourse(email_address=email_address,
                                     courses=['COMP3161']).put()

            else:
                student_course.courses.append('COMP3161')
                student_course.put()

    students = set(students)

    for student in students:
        sender = '*****@*****.**'
        subject = 'Course Review StudentSurvey'
        html = render_template('email/survey_email.haml', student=student)

        mail_kwargs = {
            'html': html,
            'body': 'TODO.txt',
            'to': student,
            'sender': sender,
            'subject': subject
        }
        mail.send_mail(**mail_kwargs)

    return json.dumps({'status': 'OK'})
예제 #55
0
    def post(self):
        username = self.request.get('email')

        user = self.user_model.get_by_auth_id(username)
        if not user:
            logging.info('Could not find any user entry for username %s', username)
            self._serve_page(not_found=True)
            return

        user_id = user.get_id()
        token = self.user_model.create_signup_token(user_id)

        verification_url = self.uri_for('verification', type='p', user_id=user_id, signup_token=token, _full=True)
        logging.debug(verification_url)
        
        mail.send_mail(sender="NYDKC Awards Committee <*****@*****.**>",
                       to=user.email,
                       subject="Resetting your DKC Application Password",
                       reply_to="*****@*****.**",
                       body="""
You have requested to change the password for your DKC Application.

If you did not authorize this, then please disregard this email. Otherwise, click the link below to reset your password.

<a href="%s">%s</a>

If you have any questions or concerns, feel free to reply to this email and we will try our best to address them!

Yours in spirit and service,
The New York District Awards Committee
                       """ % (verification_url, verification_url),
                       html="""
<h2>You have requested to change the password for your DKC Application.</h2>
<p>If you did not authorize this, then please disregard this email. Otherwise, click the link below to reset your password.</p>
<p><a href="%s">%s</a></p>
<p>If you have any questions or concerns, feel free to reply to this email and we will try our best to address them!</p>
<p>Yours in spirit and service,<br>
The New York District Awards Committee</p>
                       """ % (verification_url, verification_url)
        )
        self._serve_page(email_sent=True)
예제 #56
0
    def send(self, message, device):
        # Prepare for our request.
        params = {}
        params['collapse_key'] = message.hash()
        params['registration_id'] = device.deviceKey
        params['delay_until_idle'] = 0

        params['data.type'] = "message"
        params['data.server_id'] = message.key().id()
        params['data.source_id'] = message.source.key().id()
        params['data.device_id'] = device.key().id()
        params['data.title'] = self.encode(message.title)
        params['data.message'] = self.encode(message.message)
        if message.url:
            params['data.url'] = self.encode(message.url)
        params['data.timestamp'] = message.timestamp.isoformat()

        result = self.send_to_google(params)
        self.increment_counter('message')

        if result.status_code == 200:
            # Success!
            # The result body is a queue id. Store it.
            message.googleQueueIds.append(
                str(device.key().id()) + ": " + result.content.strip())
            message.put()
            return True
        else:
            # Failed to send. Log the error message.
            message.put()
            errorMessage = 'Unable to send message ' + str(
                message.key().id()) + ' to Google: Status code ' + str(
                    result.status_code) + ' body ' + result.content
            logging.error(errorMessage)

            # Send an email when it fails. This should not contain any private data.
            mail.send_mail(sender="Notifry <*****@*****.**>",
                           to="Notifry <*****@*****.**>",
                           subject="Error sending message",
                           body=errorMessage)
            return False
예제 #57
0
def send_new_subscriber_email(user1, playlist_model):
    user2 = playlist_model.owner

    if not user2.send_new_follower_email:
        return

    if user2.last_emailed:
        delta = datetime.now() - user2.last_emailed
        if delta.seconds < 60:
            return

    user1_display_name = get_display_name_for_youtify_user_model(user1)
    user2_display_name = get_display_name_for_youtify_user_model(user2)
    user1_profile_url = get_url_for_youtify_user_model(user1)
    unsubscribe_link = 'http://www.youtify.com/unsubscribe?uid=%s&token=%s' % (
        user2.key().id(),
        md5(EMAIL_UNSUBSCRIBE_SALT + str(user2.key().id())).hexdigest())

    body = Template(SUBSCRIBE_MAIL_TEMPLATE).substitute({
        'user1_display_name':
        user1_display_name,
        'user2_display_name':
        user2_display_name,
        'user1_profile_url':
        user1_profile_url,
        'playlist_title':
        playlist_model.title,
        'unsubscribe_link':
        unsubscribe_link,
    })

    subject = "%s now subscribes to one of your playlists!" % user1_display_name

    mail.send_mail(sender="Youtify <*****@*****.**>",
                   to="%s <%s>" %
                   (user2_display_name, user2.google_user2.email()),
                   subject=subject,
                   body=body)

    user2.last_emailed = datetime.now()
    user2.save()
예제 #58
0
 def get(self):
     """Send a reminder email to each User with an email about games that are incomplete.
     Called every hour using a cron job"""
     app_id = app_identity.get_application_id()
     games = RPS.query(RPS.game_over == False)
     for game in games:
         key_id = game.user.string_id()
         print key_id
         users = User.query(User.email == key_id)
         for user in users:
             print user.name
     # users = User.query(User.email != None)
     # for user in users:
             subject = 'You have unfinished RPS business!'
             body = 'Hello {}, settle your RPS duel - make a new move!\n Your came id is {}'.format(user.name,game.)
             # This will send test emails, the arguments to send_mail are:
             # from, to, subject, body
             mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                            user.email,
                            subject,
                            body)
예제 #59
0
    def partner_message_one_student(self,
                                    p1,
                                    p2,
                                    n1,
                                    n2,
                                    assign,
                                    message,
                                    extra=''):
        if not p1:
            return

        subject = 'ICS 31 Lab Asst. ' + str(
            assign) + ' Partnership ' + message.capitalize()

        body = 'This is an automated message from the partner app.\n\n\r'
        body += n1 + ':\n\n\rYour partnership with ' + n2 + ' for ICS 31 lab asst '
        body += str(assign) + ' has been ' + str(message) + '. ' + extra
        body += '\n\n\rIf this is a mistake, please contact your TA right away.'
        body += '\n\rNOTE: Please DO NOT reply to this message.'

        mail.send_mail(self.sender, p1.email, subject, body)
예제 #60
0
    def post(self):
        key = self.request.get('key')
        to = self.request.get('to')
        about = self.request.get('about')
        email = self.request.get('email')

        try:
            #email = to.replace(' ','.').replace('..','.') + '@dartmouth.edu'

            logging.info('ACTUALLY Mailing %s for %s' % (email, about))

            mail.send_mail(
                sender=
                'Last Chances <*****@*****.**>',
                to=email,
                subject='Last Chances Results',
                body='Your last chances match(es) are: %s.' % (about))

            #Match.get_by_key_name(key).delete()
        except:
            logging.critical('Email failed for %s' % (to))