當前位置: 首頁>>代碼示例>>Python>>正文


Python mailer.Mailer類代碼示例

本文整理匯總了Python中marrow.mailer.Mailer的典型用法代碼示例。如果您正苦於以下問題:Python Mailer類的具體用法?Python Mailer怎麽用?Python Mailer使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Mailer類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的marrow.mailer.Mailer類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。