• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pyramid_mailer.get_mailer函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: feedback

 def feedback(self):
     self.response['sent_status'] = 0
     if 'feedback.message' in self.request.params:
         msg = Validate.sanatize_textsafe(self.request.params.get('feedback.message',''))
         msg = msg + "\n\n ---------- \n"
         msg = msg + "Player: " + self.request.params.get('feedback.player','error') + "\n"
         msg = msg + "Category: " + self.request.params.get('feedback.category','error') + "\n"
         msg = msg + "From: " + self.request.params.get('feedback.from','error') + "\n"
         
         try:
             # Send to 
             emails = Properties.get('MAILER_FEEDBACK_ADDRESS').replace(' ','').split(',')
             message = Message(subject="Feedback - " + datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S"),
                               sender=self.request.user.email,
                               recipients=emails,
                               body=msg
                               )
             mailer = get_mailer(self.request)
             mailer.send(message)
             
             # Receipt
             message_receipt = Message(subject="Feedback - Receipt",
                               sender=Properties.get('MAILER_GLOBAL_FROM_ADDRESS'),
                               recipients=[self.request.user.email],
                               body="Thank you for submitting feedback. \n\n ---- \n" + Validate.sanatize_textsafe(self.request.params.get('feedback.message',''))
                               )
             mailer.send(message_receipt)
             
             self.response['sent_status'] = 2
         except Exception as e:
             self.response['sent_status'] = 1
     return self.response
开发者ID:polklibrary,项目名称:quizsmith,代码行数:32,代码来源:help.py


示例17: send_email

def send_email(subject, recipients, html, sender = None, plaintext = None, request = None, send_immediately = False, **kw):
    """ Send an email to users. This also checks the required settings and translates
        the subject.
        
        returns the message object sent, or None
    """ #FIXME: Docs
    if request is None:
        request = get_current_request()
    localizer = get_localizer(request)
    if isinstance(subject, TranslationString):
        subject = localizer.translate(subject)
    if isinstance(recipients, basestring):
        recipients = (recipients,)
    if plaintext is None:
        html2text = HTML2Text()
        html2text.ignore_links = True
        html2text.ignore_images = True
        html2text.body_width = 0
        plaintext = html2text.handle(html).strip()
    if not plaintext:
        plaintext = None #In case it was an empty string
    #It seems okay to leave sender blank since it's part of the default configuration
    msg = Message(subject = subject,
                  recipients = recipients,
                  sender = sender,
                  body = plaintext,
                  html = html,
                  **kw)
    mailer = get_mailer(request)
    #Note that messages are sent during the transaction process. See pyramid_mailer docs
    if send_immediately:
        mailer.send_immediately(msg)
    else:
        mailer.send(msg)
    return msg
开发者ID:tobsan,项目名称:voteit.core,代码行数:35,代码来源:helpers.py


示例18: test_send_thankyou_email

    def test_send_thankyou_email(self):
        request = testing.DummyRequest()
        mailer = get_mailer(request)

        self.assertEqual(len(mailer.outbox), 0)

        donation = {
            'amount': 10,
            'firstname': 'John',
            'lastname': 'Doe',
            'city': 'Springfield',
            'country': 'Exampleland',
            'state': 'Example',
            'street': 'Main Street 10',
            'zip': '12345678',
            'email': '[email protected]',
            'creation': datetime.datetime.utcnow(),
            'send_sticker': True,
        }
        send_thankyou_email(request, donation)

        self.assertEqual(len(mailer.outbox), 1)
        message = mailer.outbox[0]
        self.assertEqual(message.subject, 'Thanks for your contribution!')
        self.assertEqual(message.recipients, ['[email protected]'])
开发者ID:Yaco-Sistemas,项目名称:yith-library-server,代码行数:25,代码来源:test_email.py


示例19: confirmation

def confirmation(request):
    '''
    Generates confirmation page and confirmation emails to user and D2L site 
    admin.
    '''
    if not logged_in(request):
        return HTTPFound(location=request.route_url('login'))
    form = SelectCoursesForm()
    csrf_token = request.session.get_csrf_token()

    submitter_email = request.session['uniqueName'] + '@' + \
        request.registry.settings['EMAIL_DOMAIN']
    name = request.session['firstName'] + ' ' + request.session['lastName']
    sender = request.registry.settings['mail.username']

    '''remove for production'''
    submitter_email = '[email protected]'

    message = Message(subject="Course Combine Confirmation",
        sender=sender,
        recipients=[sender, submitter_email])
    message.body = make_msg_text(name, submitter_email, request)
    message.html = make_msg_html(name, submitter_email, request)
    mailer = get_mailer(request)
    mailer.send_immediately(message, fail_silently=False)

    return{'csrf_token': csrf_token,
        'name': name,
        'form': form, 
        'base_course': request.session['base_course'],
        'courses_to_combine': request.session['courses_to_combine']
        }
开发者ID:lookerb,项目名称:course-combine,代码行数:32,代码来源:views.py


示例20: test_send_notification_to_admins

    def test_send_notification_to_admins(self):
        request = testing.DummyRequest()
        mailer = get_mailer(request)

        self.assertEqual(len(mailer.outbox), 0)

        donation = {
            'amount': 10,
            'firstname': 'John',
            'lastname': 'Doe',
            'city': 'Springfield',
            'country': 'Exampleland',
            'state': 'Example',
            'street': 'Main Street 10',
            'zip': '12345678',
            'email': '[email protected]',
            'creation': datetime.datetime.utcnow(),
            'send_sticker': True,
            'user': None,
        }
        send_notification_to_admins(request, donation)

        self.assertEqual(len(mailer.outbox), 1)
        message = mailer.outbox[0]
        self.assertEqual(message.subject, 'A new donation was received!')
        self.assertEqual(message.recipients, self.admin_emails)
开发者ID:Yaco-Sistemas,项目名称:yith-library-server,代码行数:26,代码来源:test_email.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mailer.Mailer类代码示例发布时间:2022-05-27
下一篇:
Python compat.text_函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap