当前位置: 首页>>代码示例>>Python>>正文


Python pyramid_mailer.get_mailer函数代码示例

本文整理汇总了Python中pyramid_mailer.get_mailer函数的典型用法代码示例。如果您正苦于以下问题:Python get_mailer函数的具体用法?Python get_mailer怎么用?Python get_mailer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_mailer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_

def update_(request):
    'Update account'
    params = request.params
    if params.get('token') != request.session.get_csrf_token():
        return dict(isOk=0, message='Invalid token')
    userID = authenticated_userid(request)
    # If the user is trying to update account information, send confirmation email
    if 'username' in params:
        return save_user_(request, dict(params), 'update', db.query(User).get(userID))
    # Load
    smsAddressAction = params.get('smsAddressAction')
    # If the user is adding an SMS address,
    if 'add' == smsAddressAction:
        # Make sure it is a valid email address
        validateEmail = validators.Email().to_python
        try:
            smsAddressEmail = validateEmail(params.get('smsAddressEmail', ''))
        except Invalid, error:
            return dict(isOk=0, message=str(error))
        # Check for duplicates
        smsAddress = db.query(SMSAddress).filter(
            (SMSAddress.email == smsAddressEmail) & 
            (SMSAddress.user_id == userID)).first()
        if smsAddress:
            return dict(isOk=0, message='You already added this SMS address')
        # Add it to the database
        smsAddress = SMSAddress(email=smsAddressEmail, user_id=userID, code=make_random_string(CODE_LEN))
        db.add(smsAddress)
        # Send confirmation code
        get_mailer(request).send_to_queue(Message(
            recipients=[smsAddress.email],
            body=smsAddress.code))
        # Return smsAddresses
        return dict(isOk=1, content=render('users/smsAddresses.mak', update(request), request))
开发者ID:invisibleroads,项目名称:imap-search-scout,代码行数:34,代码来源:users.py

示例2: handle_message

 def handle_message(_, message):
     """Receive a message from nsq and send it as an email."""
     body = json.loads(message.body)
     email = pyramid_mailer.message.Message(
         subject=body["subject"], recipients=body["recipients"],
         body=body["body"])
     pyramid_mailer.get_mailer(request).send_immediately(email)
开发者ID:badgettrg,项目名称:Webmarks,代码行数:7,代码来源:mailer.py

示例3: test_valid

    def test_valid(self):
        req = DummyRequest(post={
            'password': 'newpw',
            'password2': 'newpw',
        })
        req.matchdict['token'] = self.token.token
        req.remote_addr = '127.0.0.1'
        resp = views.account.reset(req)
        self.assertIsInstance(resp, httpexceptions.HTTPMovedPermanently)
        self.assertTrue(resp.location.endswith('/account/login'))

        registry = self.config.registry
        mailer = get_mailer(registry)
        self.assertEqual(len(mailer.outbox), 1)

        # Should not be able to use a token > 1 time
        req = DummyRequest(post={
            'password': 'newpw',
            'password2': 'newpw',
        })
        req.matchdict['token'] = self.token.token
        req.remote_addr = '127.0.0.1'
        resp = views.account.reset(req)
        self.assertIsInstance(resp, httpexceptions.HTTPMovedPermanently)
        self.assertTrue(resp.location.endswith('/account/forgot'))

        registry = self.config.registry
        mailer = get_mailer(registry)
        self.assertEqual(len(mailer.outbox), 1)
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:29,代码来源:views_account.py

示例4: cne_created

def cne_created(event):
    manage_url = event.request.route_url('defcne.e', traverse=(event.cne.dc, event.cne.id, 'manage'))
    text = __staff_eventcreated__.format(contest_name=event.cne.disp_name, contest_owner=event.request.user.user.disp_uname, event_manage_url=manage_url)

    staff_list = m.Group.find_group(u'staff').users
    staff_emails = [user.email for user in staff_list]

    message = Message(subject="DEFCnE Contest/Event Created", sender="[email protected]", recipients=staff_emails, body=text)
    get_mailer(event.request).send(message)
开发者ID:bertjwregeer,项目名称:defcne,代码行数:9,代码来源:__init__.py

示例5: sing_up

def sing_up(request):
    sign_up_form = forms.SignUpForm(csrf_context=request)
    successful_submission = False
    if request.method == 'POST':
        sign_up_form.process(request.POST)
        if sign_up_form.validate():
            user = User(
                email=sign_up_form.email.data.lower(),
                phone=sign_up_form.phone.data,
                name=sign_up_form.user_name.data,
                company_name=(
                    sign_up_form.company_name.data
                    if sign_up_form.company_name.data else
                    None
                ),
                timezone_tzname=str(request.registry['default_timezone'])
            )
            user.set_password(sign_up_form.password.data)
            DBSession.add(user)
            template = request.registry['jinja2_environment'].get_template(
                'sngconnect.accounts:templates/emails/account_activation.txt'
            )
            activation_email = EmailMessage(
                subject=_("Activate your account at SNG Connect"),
                sender=request.registry['settings']['mail.sender'],
                recipients=[user.email],
                body=template.render(
                    activation_url=request.route_url(
                        'sngconnect.accounts.activate',
                        email=user.email,
                        email_activation_code=user.email_activation_code
                    )
                )
            )
            get_mailer(request).send(activation_email)
            sms_service = SMSService(request.registry)
            sms_service.send_sms(
                [user.phone],
                _(
                    "Your SNG:connect confirmation code is: ${code}",
                    mapping={
                        'code': user.phone_activation_code,
                    }
                )
            )
            successful_submission = True
    return {
        'sign_up_form': sign_up_form,
        'successful_submission': successful_submission,
    }
开发者ID:fikander,项目名称:sngtec-sngconnect,代码行数:50,代码来源:views.py

示例6: test_send_passwords

    def test_send_passwords(self):
        preferences_link = 'http://localhost/preferences'
        backups_link = 'http://localhost/backups'
        user_id = self.db.users.insert({
                'first_name': 'John',
                'last_name': 'Doe',
                'email': '[email protected]',
                }, safe=True)
        user = self.db.users.find_one({'_id': user_id})

        request = DummyRequest()
        request.db = self.db
        mailer = get_mailer(request)

        self.assertFalse(send_passwords(request, user,
                                        preferences_link, backups_link))
        self.assertEqual(len(mailer.outbox), 0)

        # add some passwords
        self.db.passwords.insert({
                'owner': user_id,
                'password': 'secret1',
                })
        self.db.passwords.insert({
                'owner': user_id,
                'password': 'secret2',
                })

        request = DummyRequest()
        request.db = self.db
        request.date_service = FakeDateService(request)
        mailer = get_mailer(request)

        os.environ['YITH_FAKE_DATE'] = '2012-1-10'

        self.assertTrue(send_passwords(request, user,
                                       preferences_link, backups_link))
        self.assertEqual(len(mailer.outbox), 1)
        message = mailer.outbox[0]
        self.assertEqual(message.subject, "Your Yith Library's passwords")
        self.assertEqual(message.recipients, ['[email protected]'])
        self.assertTrue(preferences_link in message.body)
        self.assertTrue(backups_link in message.body)
        self.assertEqual(len(message.attachments), 1)
        attachment = message.attachments[0]
        self.assertEqual(attachment.content_type, 'application/yith')
        self.assertEqual(attachment.filename,
                         'yith-library-backup-2012-01-10.yith')

        del os.environ['YITH_FAKE_DATE']
开发者ID:Yaco-Sistemas,项目名称:yith-library-server,代码行数:50,代码来源:test_email.py

示例7: errmail_tween

 def errmail_tween(request, subject=subject):
     try:
         return handler(request)
     except Exception, e:
         try:
             exc_info = sys.exc_info()
             mailer = get_mailer(request)
             exc_repr = repr(e)[:200]
             localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
             gmtime = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
             mapping = {'localtime':localtime,
                        'gmtime':gmtime,
                        'hostname':hostname,
                        'exception':exc_repr}
             def replace(match):
                 whole, param1, param2 = match.groups()
                 return mapping.get(param1 or param2, whole)
             subject = _interp_regex.sub(replace, subject)
             html = cgitb.html(exc_info)
             header = request.url
             html = '<html><h1>%s</h1>%s</html>' % (header, html)
             body = ''.join(traceback.format_exception(*exc_info))
             body = '%s\n\n%s' % (header, body)
             message = Message(subject=subject,
                               sender=sender,
                               recipients=recipients,
                               html=html,
                               body=body)
             mailer.send_immediately(message, fail_silently=True)
             raise
         finally:
             del exc_info
开发者ID:marcv,项目名称:pyramid_errmail,代码行数:32,代码来源:__init__.py

示例8: password_reset

def password_reset(request):
    email = request.params.get('email')
    try:
        session = DBSession()
        user = DBSession.query(User).filter_by(email=email).one()
        ptoken = DBSession.query(PasswordResetToken).get(user.id)
        if not ptoken:
            ptoken = PasswordResetToken(user_id=user.id)
        token = str(uuid4())
        ptoken.token = token 
        session.add(ptoken)
    except NoResultFound:
        token = None

    if token:
#        settings = request.registry.settings
        mailer = get_mailer(request)
        headers = {"header": u'Password reset',
                   "message": u'Please click on the link bellow to reset your penelope account\'s password.',
                   "link": '%s/change_password?token=%s' % (request.application_url, token),
                   "action": 'Reset password'}
        message = Message(subject=u"Password reset request",
                          recipients=[email],
                          body=u'Password reset',
                          extra_headers={'X-MC-Template': 'general',
                                         'X-MC-MergeVars': json.dumps(headers)})
        mailer.send(message)
    return {'request': request, 'token': token}
开发者ID:getpenelope,项目名称:por.dashboard,代码行数:28,代码来源:views.py

示例9: success_check_email

def success_check_email(request):
    """
    This view just returns a note to go check mail
    """
    #check if user has used form or 'guessed' this URL
    if ('appstruct' in request.session):
        # we do have valid info from the form in the session
        appstruct = request.session['appstruct']
        from pyramid_mailer.message import Message
        mailer = get_mailer(request)
        # XXX TODO: check for locale, choose language for body text
        the_mail = Message(
            subject=_("C3S: confirm your email address and load your PDF"),
            sender="[email protected]",
            recipients=[appstruct['email']],
            body="""hello %s %s,

please use this link to verify your email address
and download your personal Declaration of Intent PDF:

https://yes.c3s.cc/verify/%s/%s
""" % (appstruct['firstname'],
       appstruct['lastname'],
       appstruct['email'],
       appstruct['email_confirm_code'])
        )
        mailer.send(the_mail)
        return {
            'firstname': appstruct['firstname'],
            'lastname': appstruct['lastname'],
        }
    # 'else': send user to the form
    return HTTPFound(location=request.route_url('intent'))
开发者ID:C3S,项目名称:C3SIntent,代码行数:33,代码来源:views.py

示例10: send_change_password_email

def send_change_password_email(
        request, profile, email=None):
    mailer = get_mailer(request)
    localizer = request.localizer
    data = dict(
        name=profile.name, assembl="Assembl",
        confirm_url=maybe_contextual_route(
            request, 'do_password_change',
            ticket=password_token(profile)))
    message = Message(
        subject=localizer.translate(
            _("Request for password change"), mapping=data),
        sender=config.get('assembl.admin_email'),
        recipients=["%s <%s>" % (
            profile.name, email or profile.get_preferred_email())],
        body=localizer.translate(_(u"""Hello, ${name}!
We have received a request to change the password on your ${assembl} account.
To confirm your password change please click on the link below.
<${confirm_url}>

If you did not ask to reset your password please disregard this email.

Best regards,
The ${assembl} Team
"""), mapping=data),
        html=localizer.translate(_(u"""<p>Hello, ${name}!</p>
<p>We have received a request to change the password on your ${assembl} account.
Please <a href="${confirm_url}">click here to confirm your password change</a>.</p>
<p>If you did not ask to reset your password please disregard this email.</p>
<p>Best regards,<br />The ${assembl} Team</p>
"""), mapping=data))
    # if deferred:
    #    mailer.send_to_queue(message)
    # else:
    mailer.send(message)
开发者ID:rmoorman,项目名称:assembl,代码行数:35,代码来源:views.py

示例11: password_reminder

def password_reminder(email, request):
    """
    For an email address, find the corresponding team and send a password
    reset token. If no team is found send an email that no user was found for
    this address.
    """
    mailer = get_mailer(request)
    team = DBSession.query(Team).filter(Team.email == email).first()
    if team:
        # send mail with reset token
        team.reset_token = random_token()
        html = render('mail_password_reset_valid.mako', {'team': team},
                      request=request)
        recipients = [team.email]
    else:
        # send mail with information that no team was found for that address.
        html = render('mail_password_reset_invalid.mako', {'email': email},
                      request=request)
        recipients = [email]
    competition = request.registry.settings['competition_title']
    message = Message(subject="Password Reset for %s" % competition,
                      recipients=recipients,
                      html=html,
                      )
    mailer.send(message)
    return team
开发者ID:Immortalem,项目名称:fluxscoreboard,代码行数:26,代码来源:team.py

示例12: notify_account_created

def notify_account_created(event):
    """Notify site admins when an account is created.
    """
    logger = getLogger('speak_friend.user_activity')
    path = 'speak_friend:templates/email/account_creation_notification.pt'
    settings = event.request.registry.settings
    subject = '%s: New user created' % settings['site_name']
    mailer = get_mailer(event.request)
    headers = {'Reply-To': event.user.full_email}
    response = render_to_response(path,
                                  {'profile': event.user},
                                  event.request)
    # Obtain list of emails to notify from the control panel
    cp = ControlPanel(event.request)
    recipients = cp.get_value(email_notification_schema.name,
                              'user_creation', [])
    if not recipients:
        logger.info('No one to notify of account creation: %s.',
                    event.user)
        return

    message = Message(subject=subject,
                      sender=settings['site_from'],
                      recipients=recipients,
                      extra_headers=headers,
                      html=response.unicode_body)
    mailer.send(message)
开发者ID:sixfeetup,项目名称:speak_friend,代码行数:27,代码来源:subscribers.py

示例13: create_user

def create_user(request):
	user 		 = request.validated['user']
	username = user['username']
	email 	 = user['email']
	token    = user['token']
	password = user['password']
	activationToken = user['activationToken']
	userID	 = uuid.uuid4()
	user_data  = {
							'username' 				 : username, 
							'email'		 				 : email, 
							'token' 	 				 : token, 
							'password' 				 : password,
							'activation_token' : activationToken,
							'account_active' 	 : False }

	request.db.users.insert({ '_id' : str(userID), 'profile' : user_data })

	mailer  = get_mailer(request)
	message = Message(subject="Welcome to DuD " + username,
                  sender="[email protected]",
                  recipients=["[email protected]"],
                  body="hello " + username + 
                  			"!<a href='"
                  			+ base_url + "activate-account/" + activationToken +"'>"
                  			"Click here</a>" 
                  			"to activate your account" )

	mailer.send_immediately(message)

	return {'type' : 'true', 'response' : 'user successifully created', 'token' : token }
开发者ID:Popcore,项目名称:FreeB,代码行数:31,代码来源:signup.py

示例14: setUp

    def setUp(self):  # noqa
        self.app = TestApp(self.app)
        registry = self.app.app.registry
        self.mailer = get_mailer(registry)
        self.email_service = EmailService(self.mailer, settings)
        EmailService.instance = None

        self.config = testing.setUp()

        self.connection = self.engine.connect()

        # begin a non-ORM transaction
        self.trans = self.connection.begin()

        # DBSession is the scoped session manager used in the views,
        # reconfigure it to use this test's connection
        DBSession.configure(bind=self.connection)

        # create a session bound to the connection, this session is the one
        # used in the test code
        self.session = self.Session(bind=self.connection)

        self.queue_config = registry.queue_config
        reset_queue(self.queue_config)
        reset_cache_key()
开发者ID:c2corg,项目名称:v6_api,代码行数:25,代码来源:__init__.py

示例15: create_activation

def create_activation(request, user):
    db = get_session(request)
    Activation = request.registry.getUtility(IActivationClass)
    activation = Activation()

    db.add(activation)
    user.activation = activation

    db.flush()

    # TODO Create a hook for the app to give us body and subject!
    # TODO We don't need pystache just for this!
    body = pystache.render(
        _("Please validate your email and activate your account by visiting:\n"
            "{{ link }}"),
        {
            'link': request.route_url('activate', user_id=user.id,
                                      code=user.activation.code)
        }
    )
    subject = _("Please activate your account!")

    message = Message(subject=subject, recipients=[user.email], body=body)
    mailer = get_mailer(request)
    mailer.send(message)
开发者ID:ajkaanbal,项目名称:horus,代码行数:25,代码来源:__init__.py


注:本文中的pyramid_mailer.get_mailer函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。