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

Python mailer.Mailer类代码示例

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

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



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

示例1: test_send

    def test_send(self):
        message = Bunch(id="foo")

        interface = Mailer(base_config)

        with pytest.raises(MailerNotRunning):
            interface.send(message)

        interface.start()

        # logging.getLogger().handlers[0].truncate()
        # messages = logging.getLogger().handlers[0].buffer

        assert interface.send(message) == (message, True)

        # assert messages[0] == "Attempting delivery of message foo."
        # assert messages[-1] == "Message foo delivered."

        message_fail = Bunch(id="bar", die=True)

        with pytest.raises(Exception):
            interface.send(message_fail)

            # assert messages[-4] == "Attempting delivery of message bar."
            # assert messages[-3] == "Acquired existing transport instance."
            # assert messages[-2] == "Shutting down transport due to unhandled exception."
            # assert messages[-1] == "Delivery of message bar failed."

        interface.stop()
开发者ID:nandoflorestan,项目名称:marrow.mailer,代码行数:29,代码来源:test_core.py


示例2: _get_mailer

def _get_mailer(request):
	global _mailer, _last_change

	if _mailer:
		if _last_change != request.config['_last_change']:
			mailer = _mailer
			_mailer = None
			stop_mailer(mailer)

	if not _mailer:
		transport = {
			'use': 'smtp',
			'host': os.environ.get('CIOC_MAIL_HOST', '127.0.0.1'),
			'username': os.environ.get('CIOC_MAIL_USERNAME'),
			'password': os.environ.get('CIOC_MAIL_PASSWORD'),
			'port': os.environ.get('CIOC_MAIL_PORT'),
			'tls': 'ssl' if os.environ.get('CIOC_MAIL_USE_SSL') else None,
		}
		# print transport['host']
		transport = {k: v for k, v in transport.iteritems() if v}
		_mailer = Mailer({
			'transport': transport,
			'manager': {'use': request.config.get('mailer.manager', 'immediate')}
		})
		_mailer.start()

	return _mailer
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:27,代码来源:email.py


示例3: test_new

    def test_new(self):
        config = dict(
            manager=dict(use="immediate"),
            transport=dict(use="mock"),
            message=dict(author="[email protected]", retries=1, brand=False),
        )

        interface = Mailer(config).start()
        message = interface.new(retries=2)

        assert message.author == ["[email protected]"]
        assert message.bcc == []
        assert message.retries == 2
        assert message.mailer is interface
        assert message.brand == False

        with pytest.raises(NotImplementedError):
            Message().send()

        assert message.send() == (message, True)

        message = interface.new("[email protected]", "[email protected]", "Test.")

        assert message.author == ["[email protected]"]
        assert message.to == ["[email protected]"]
        assert message.subject == "Test."
开发者ID:nandoflorestan,项目名称:marrow.mailer,代码行数:26,代码来源:test_core.py


示例4: includeme

def includeme(config):
    """Configure marrow.mailer"""
    settings = config.registry.settings
    prefix = settings.get('pyramid_marrowmailer.prefix', 'mail.').rstrip('.')

    # handle boolean options and int options .digit .on
    mailer_config = dict(filter(lambda d: d[0].startswith(prefix),
                                settings.items()))
    for key, value in dict(mailer_config).items():
        if key.endswith('.on'):
            mailer_config[key[:-3]] = asbool(value)
        if key.endswith('.int'):
            mailer_config[key[:-4]] = int(value)

    # bugfix for https://github.com/marrow/marrow.mailer/issues/45
    manager = '%s.manager.use' % prefix
    if manager not in mailer_config:
        mailer_config[manager] = 'immediate'

    mode = '%s.mode' % prefix
    if mailer_config.get(mode) == 'direct':
        mailer = Mailer(mailer_config, prefix)
    else:
        mailer = TransactionMailer(mailer_config, prefix)

    mailer.start()

    config.registry.registerUtility(mailer, IMarrowMailer)
    config.set_request_property(get_mailer, "mailer", reify=True)

    # shutdown mailer when process stops
    atexit.register(lambda: mailer.stop())
开发者ID:kralla,项目名称:pyramid_marrowmailer,代码行数:32,代码来源:__init__.py


示例5: test_issue_2

def test_issue_2():
    mail = Mailer({
            'manager.use': 'immediate',
            'transport.use': 'smtp',
            'transport.host': 'secure.emailsrvr.com',
            'transport.tls': 'ssl'
        })
    
    mail.start()
    mail.stop()
开发者ID:cynepiaadmin,项目名称:mailer,代码行数:10,代码来源:test_issue_2.py


示例6: MailingAdapter

class MailingAdapter(object):

    def __init__(self, host, port):
        self.mailer = Mailer(dict(
            manager = dict(
                use = 'immediate'),
            transport = dict(
                use = 'smtp',
                port = port,
                host = host)))
        self.mailer.start()

    def send_mail(self, to_address, from_address, body):
        message = Message(author=from_address, to=to_address)
        message.subject = "Testing Marrow Mailer"
        message.plain = body
        self.mailer.send(message)
开发者ID:philipcristiano,项目名称:transporter,代码行数:17,代码来源:mailing_adapter.py


示例7: MailHandler

class MailHandler(logging.Handler):
    """A class which sends records out via e-mail.
    
    This handler should be configured using the same configuration
    directives that Marrow Mailer itself understands.
    
    Be careful how many notifications get sent.
    
    It is suggested to use background delivery using the 'dynamic' manager.
    """
    
    def __init__(self, *args, **config):
        """Initialize the instance, optionally configuring TurboMail itself.
        
        If no additional arguments are supplied to the handler, re-use any
        existing running TurboMail configuration.
        
        To get around limitations of the INI parser, you can pass in a tuple
        of name, value pairs to populate the dictionary.  (Use `{}` dict
        notation in produciton, though.)
        """
        
        logging.Handler.__init__(self)
        
        self.config = dict()
        
        if args:
            config.update(dict(zip(*[iter(args)]*2)))
        
        self.mailer = Mailer(config).start()
        
        # If we get a configuration that doesn't explicitly start TurboMail
        # we use the configuration to populate the Message instance.
        self.config = config
    
    def emit(self, record):
        """Emit a record."""
        
        try:
            self.mailer.new(plain=self.format(record)).send()
        
        except (KeyboardInterrupt, SystemExit):
            raise
        
        except:
            self.handleError(record)
开发者ID:DatatracCorporation,项目名称:marrow.mailer,代码行数:46,代码来源:logger.py


示例8: __init__

 def __init__(self, username="", password="", use="smtp", host="smtp.exmail.qq.com", port="25"):
     self.username = username
     self.mailer = Mailer(
         {
             "transport": {"use": use, "host": host, "port": port, "username": username, "password": password},
             "manager": {},
         }
     )
开发者ID:Brightcells,项目名称:thingsforinternet,代码行数:8,代码来源:send_email.py


示例9: send_mail_via_smtp_

    def send_mail_via_smtp_(config, payload):
        """
        Send email via SMTP
        :param config:
        :param payload:
        :return:
        """
        mailer_config = {
            'transport': {
                'use': 'smtp',
                'host': config['host'],
                'username': config['username'],
                'password': config['password'],
                'tls': config['encryption'],
                'port': config['port']
            }
        }

        mailer = Mailer(mailer_config)
        mailer.start()
        message = Message(author=payload['from'], to=payload['to'])
        message.subject = payload['subject']
        message.plain = strip_tags(payload['html'])
        message.rich = payload['html']
        mailer.send(message)
        mailer.stop()
开发者ID:PareshMayani,项目名称:open-event-android,代码行数:26,代码来源:notification.py


示例10: __init__

 def __init__(self, host, port):
     self.mailer = Mailer(dict(
         manager = dict(
             use = 'immediate'),
         transport = dict(
             use = 'smtp',
             port = port,
             host = host)))
     self.mailer.start()
开发者ID:philipcristiano,项目名称:transporter,代码行数:9,代码来源:mailing_adapter.py


示例11: __init__

 def __init__(self):
     self.config = Config().config['mail']
     self.mailer = MarrowMailer(
         dict(
             transport=dict(debug=True,
                            **self.config),
             manager=dict(),
             ),
         )
开发者ID:ncgaskin,项目名称:mentor-finder,代码行数:9,代码来源:mailers.py


示例12: __init__

 def __init__(self):
     self.mailer = Mailer(dict(
         transport=dict(
             use='smtp',
             host='smtp.gmail.com',
             port='587',
             username=username,
             password=password,
             tls='required',
             debug=False),
         manager=dict()))
     self.mailer.start()
开发者ID:roopeshvaddepally,项目名称:bayareahash,代码行数:12,代码来源:mail.py


示例13: test_send

 def test_send(self):
     message = Bunch(id='foo')
     
     interface = Mailer(base_config)
     
     self.assertRaises(MailerNotRunning, interface.send, message)
     
     interface.start()
     
     logging.getLogger().handlers[0].truncate()
     messages = logging.getLogger().handlers[0].buffer
     
     self.assertEqual(interface.send(message), (message, True))
     
     self.assertEqual(messages[0].getMessage(), "Attempting delivery of message foo.")
     self.assertEqual(messages[-1].getMessage(), "Message foo delivered.")
     
     message_fail = Bunch(id='bar', die=True)
     self.assertRaises(Exception, interface.send, message_fail)
     
     self.assertEqual(messages[-4].getMessage(), "Attempting delivery of message bar.")
     self.assertEqual(messages[-3].getMessage(), "Acquired existing transport instance.")
     self.assertEqual(messages[-2].getMessage(), "Shutting down transport due to unhandled exception.")
     self.assertEqual(messages[-1].getMessage(), "Delivery of message bar failed.")
     
     interface.stop()
开发者ID:DatatracCorporation,项目名称:marrow.mailer,代码行数:26,代码来源:test_core.py


示例14: send_email

def send_email(send_to, templaterich, templateplain, subject, **kwargs):
    """
        Sends an email to the target email with two types
            1) HTML
            2) Plain

        We will try the template with .htm for rich and .txt for plain.

        Both will rendered with Jinja2
    """

    mailer = Mailer(dict(
        transport=dict(use='smtp', host=config.EMAIL_SMTP_SERVER, debug=config.EMAIL_DEBUG),
        manager=dict()))

    mailer.start()

    message = mailer.new()
    message.author = config.EMAIL_SENDER
    message.to = send_to
    message.subject = subject

    template_rich = env.get_template(templaterich)
    template_plain = env.get_template(templateplain)

    message.rich = template_rich.render(**kwargs)
    message.plain = template_plain.render(**kwargs)

    logger.info('Sent an email to ' + send_to)

    message.send()
    mailer.stop()
开发者ID:haukurk,项目名称:earthquake-notifier,代码行数:32,代码来源:listener.py


示例15: test_new

 def test_new(self):
     config = dict(manager=dict(use='immediate'), transport=dict(use='mock'),
             message=dict(author='[email protected]', retries=1, brand=False))
     
     interface = Mailer(config).start()
     message = interface.new(retries=2)
     
     self.assertEqual(message.author, ["[email protected]"])
     self.assertEqual(message.bcc, [])
     self.assertEqual(message.retries, 2)
     self.assertTrue(message.mailer is interface)
     self.assertEqual(message.brand, False)
     
     self.assertRaises(NotImplementedError, Message().send)
     
     self.assertEqual(message.send(), (message, True))
     
     message = interface.new("[email protected]", "[email protected]", "Test.")
     
     self.assertEqual(message.author, ["[email protected]"])
     self.assertEqual(message.to, ["[email protected]"])
     self.assertEqual(message.subject, "Test.")
开发者ID:DatatracCorporation,项目名称:marrow.mailer,代码行数:22,代码来源:test_core.py


示例16: __init__

    def __init__(self, pkg_name, config=None,  server='localhost',
                  username=None, password=None, email_port=25,
                  default_sender=None, template_dir='email_templates'):
        """
        Can be created by passing the configuration for sending a mail,
        pkg_name is required so we can find your email templates but depending
        on your configuration server, username, password may not be required.

        Only server, username, password, port, sender and template_dir can be
        configured.  If you need to change other settings such as logging.
        Please pass a Config object.
        """
        if not config is None:
            self._config = config
        else:
            self._config = Config()
            if not server is None:
                self._config.EMAIL_HOST = server
            if not username is None:
                self._config.EMAIL_USERNAME = username
            if not password is None:
                self._config.EMAIL_PWD = password
            if not email_port is None:
                self._config.EMAIL_PORT = email_port
            if not default_sender is None:
                self._config.EMAIL_SENDER = default_sender
            self._config.EMAIL_TEMPLATE_DIR = template_dir

        #Init log
        self._log = logging.getLogger(self._config.LOGGER_NAME)
        self._log.setLevel(self._config.LOGGER_LEVEL)
        console_handler = logging.StreamHandler()
        self._log.addHandler(console_handler)

        #Init Jinja
        self._jinja_env = Environment(loader=PackageLoader(pkg_name,
            self._config.EMAIL_TEMPLATE_DIR))

        #Init Mailer
        self._mailer = Mailer(dict(
            transport = dict(
                use = 'smtp',
                host = self._config.EMAIL_HOST,
                username = self._config.EMAIL_USERNAME,
                password = self._config.EMAIL_PWD,
                port = self._config.EMAIL_PORT),
            manager = dict()))

        self._mailer.start()
开发者ID:Dotnetwill,项目名称:marrja_mail,代码行数:49,代码来源:__init__.py


示例17: test_shutdown

    def test_shutdown(self):
        interface = Mailer(base_config)
        interface.start()

        # logging.getLogger().handlers[0].truncate()
        # messages = logging.getLogger().handlers[0].buffer

        interface.stop()

        # assert len(messages) == 5
        # assert messages[0] == "Mail delivery service stopping."
        # assert messages[-1] == "Mail delivery service stopped."

        interface.stop()
开发者ID:nandoflorestan,项目名称:marrow.mailer,代码行数:14,代码来源:test_core.py


示例18: passwdreset

 def passwdreset(self):
     """Render password reset page"""
     c.came_from = '/'
     c.login_counter = 0
     c.form = ResetPwForm(request.POST, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         key_seed = '%s%s' % (c.form.email.data, arrow.utcnow().ctime())
         token = hashlib.sha1(key_seed).hexdigest()
         user = Session.query(User)\
                         .filter(User.email == c.form.email.data)\
                         .one()
         if not user.local:
             flash(_('The account %s is an external account, use your'
                     ' External systems to change the password. '
                     'Contact your system adminstrator if you do not '
                     'know which external systems you authenticate to')
                     % user.email)
             redirect(url('/accounts/login'))
         rtoken = Session\
                 .query(ResetToken.used)\
                 .filter(ResetToken.used == false())\
                 .filter(ResetToken.user_id == user.id)\
                 .all()
         if not rtoken:
             rtoken = ResetToken(token, user.id)
             Session.add(rtoken)
             Session.commit()
             host = URL_PREFIX_RE.sub('', request.host_url)
             c.username = user.username
             c.firstname = user.firstname or user.username
             c.reset_url = url('accounts-pw-token-reset',
                             token=token,
                             host=host)
             text = self.render('/email/pwreset.txt')
             mailer = Mailer(get_conf_options(config))
             mailer.start()
             sdrnme = config.get('baruwa.custom.name', 'Baruwa')
             email = Msg(author=[(sdrnme,
                         config.get('baruwa.reports.sender'))],
                         to=[('', c.form.email.data)],
                         subject=_("[%s] Password reset request") % sdrnme)
             email.plain = text
             mailer.send(email)
             mailer.stop()
         flash(_('An email has been sent to the address provided, '
                 'please follow the instructions in that email to '
                 'reset your password.'))
         redirect(url('/accounts/login'))
     return self.render('/accounts/login.html')
开发者ID:baruwaproject,项目名称:baruwa2,代码行数:49,代码来源:accounts.py


示例19: command

    def command(self):
        "run command"
        self.init()
        self.language = 'en'
        self.host_url = self.conf['baruwa.default.url']
        self.send_from = self.conf['baruwa.reports.sender']
        self.num_of_days = self.options.number_of_days
        base = workout_path()
        path = os.path.join(base, 'baruwa', 'templates')
        self.logo = os.path.join(base, 'baruwa', 'public', 'imgs', 'logo.png')
        self.localedir = os.path.join(base, 'baruwa', 'i18n')
        cache_dir = os.path.join(self.conf['cache_dir'], 'templates')

        self.mako_lookup = TemplateLookup(
                        directories=[path],
                        error_handler=handle_mako_error,
                        module_directory=cache_dir,
                        input_encoding='utf-8',
                        default_filters=['escape'],
                        output_encoding='utf-8',
                        encoding_errors='replace',
                        imports=['from webhelpers.html import escape']
                        )

        self.mailer = Mailer(get_conf_options(self.conf))
        self.mailer.start()
        if self.options.report_type == 'user':
            users = get_users()
            for user in users:
                self._process_user_report(user)
        else:
            period = REPORTS_MAP[self.options.report_period]
            domains = Session.query(Domain).filter(Domain.status == True)\
                            .filter(Domain.report_every == period).all()
            for domain in domains:
                admins = set()
                self.translator = set_lang(domain.language,
                                            PKGNAME,
                                            self.localedir)
                for org in domain.organizations:
                    for admin in org.admins:
                        admins.add(admin)
                pdf_file = self._process_domain_report(domain)
                for admin in admins:
                    self._send_domain_report(pdf_file, domain.site_url, admin)
        self.mailer.stop()
开发者ID:TetraAsh,项目名称:baruwa2,代码行数:46,代码来源:pdfreportsng.py


示例20: test_startup

    def test_startup(self):
        # messages = logging.getLogger().handlers[0].buffer

        interface = Mailer(base_config)
        interface.start()

        # assert len(messages) == 5
        # assert messages[0] == "Mail delivery service starting."
        # assert messages[-1] == "Mail delivery service started."

        interface.start()

        # assert len(messages) == 6
        # assert messages[-1] == "Attempt made to start an already running Mailer service."

        interface.stop()
开发者ID:nandoflorestan,项目名称:marrow.mailer,代码行数:16,代码来源:test_core.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python compat.unicode函数代码示例发布时间:2022-05-27
下一篇:
Python _speedups.escape函数代码示例发布时间: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