本文整理汇总了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()
示例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
示例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."
示例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())
示例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()
示例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)
示例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)
示例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": {},
}
)
示例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()
示例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()
示例11: __init__
def __init__(self):
self.config = Config().config['mail']
self.mailer = MarrowMailer(
dict(
transport=dict(debug=True,
**self.config),
manager=dict(),
),
)
示例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()
示例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()
示例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()
示例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.")