Пример #1
0
	def test_transport_dotcolon_failure(self):
		config = {
				'manager.use': 'immediate',
				'transport.use': 'marrow.mailer.transport.foo:FooTransport'
			}

		log.info("Testing configuration: %r", dict(config))
		with pytest.raises(ImportError):
			Mailer(config)

		config['manager.use'] = 'marrow.mailer.transport.mock:FooTransport'
		log.info("Testing configuration: %r", dict(config))
		with pytest.raises(AttributeError):
			Mailer(config)
Пример #2
0
def send_mail(subj,
              body,
              bifogade_filer,
              recipients=[],
              sender='*****@*****.**'):
    from marrow.mailer import Mailer, Message
    """Send mail to specified recipients."""
    recipients = [*recipients]
    mailer = Mailer(dict(transport=dict(use='smtp', host='smtp.gu.se')))

    mailer.start()
    message = Message(
        subject=f'{subj}',
        plain=f'{body}',
        author=sender,
        to=recipients,
    )
    if bifogade_filer:
        for fil in bifogade_filer:
            if not os.path.isfile(fil):
                message.plain += "\n"
                message.plain += f"Error: attempted attachment {fil} does not appear to exist"
            else:
                message.attach(str(fil))
    nl = "\n"
    message.plain += f"{nl}{nl}If you have any question you can reach us at:"
    message.plain += f"{nl}[email protected]"
    message.plain += f"{nl}"
    message.plain += f"{nl}Best regards,"
    message.plain += f"{nl}Clinical Genomics Gothenburg"
    mailer.send(message)
Пример #3
0
def send_report_mail(plain_text, settings):
    """Send anomalies report by email

    Arguments:
        plain_text {string} -- Report body in plain text
        settings (dict) -- Settings from the class Config.Smtp

    Returns:
    """

    mailer = Mailer({
        'manager.use': 'futures',
        'transport.use': 'smtp',
        'transport.host': settings['host'],
        'transport.tls': settings['ssl'],
        'transport.debug': False,
        'transport.username': settings['username'],
        'transport.password': settings['password'],
        'transport.max_messages_per_connection': 5
    })

    mailer.start()

    message = Message(author=settings['mailfrom'], to=settings['mailto'])
    message.subject = settings['subject']
    message.plain = plain_text

    mailer.send(message)
    mailer.stop()

    return True
Пример #4
0
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 False,
        }
        # print transport['host']
        transport = {k: v for k, v in transport.items() if v is not None}

        manager = request.config.get("mailer.manager", "immediate")
        if manager == "dynamic":
            manager = DynamicManagerHotFix

        _mailer = Mailer({"transport": transport, "manager": {"use": manager}})
        _mailer.start()

    return _mailer
Пример #5
0
def send_email_task_smtp(payload, smtp_config, headers=None):
    mailer_config = {
        'transport': {
            'use': 'smtp',
            'host': smtp_config['host'],
            'username': smtp_config['username'],
            'password': smtp_config['password'],
            'tls': smtp_config['encryption'],
            'port': smtp_config['port']
        }
    }

    try:
        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']
        if payload['attachments'] is not None:
            for attachment in payload['attachments']:
                message.attach(name=attachment)
        mailer.send(message)
        logging.info('Message sent via SMTP')
    except urllib.error.HTTPError as e:
        if e.code == 554:
            empty_attachments_send(mailer, message)
    mailer.stop()
Пример #6
0
	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()
Пример #7
0
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.add_request_method(get_mailer, "mailer", reify=True)

    # shutdown mailer when process stops
    atexit.register(lambda: mailer.stop())
Пример #8
0
    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()
Пример #9
0
 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()
Пример #10
0
def init_app(app):
    marrowmailer_config_key = 'MARROWMAILER_CONFIG'

    if marrowmailer_config_key not in app.config:
        app.config[marrowmailer_config_key] = _get_config(app)

    mailer_config = app.config.get(marrowmailer_config_key)

    app.marrowmailer = Mailer(mailer_config)
Пример #11
0
	def test_manager_entrypoint_failure(self):
		config = {
				'manager.use': 'immediate2',
				'transport.use': 'mock'
			}

		log.info("Testing configuration: %r", dict(config))
		with pytest.raises(LookupError):
			Mailer(config)
Пример #12
0
def test_issue_2():
    mail = Mailer({
        'manager.use': 'immediate',
        'transport.use': 'smtp',
        'transport.host': 'secure.emailsrvr.com',
        'transport.tls': 'ssl'
    })

    mail.start()
    mail.stop()
Пример #13
0
 def test_deep_prefix(self):
     config = {
             'marrow.mailer.manager.use': 'immediate',
             'marrow.mailer.transport.use': 'mock'
         }
     
     log.info("Testing configuration: %r", dict(config))
     a = Mailer(config, 'marrow.mailer')
     
     self.assertEqual(a.Manager, ImmediateManager)
     self.assertEqual(a.Transport, MockTransport)
Пример #14
0
    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()
Пример #15
0
	def test_prefix(self):
		config = {
				'mail.manager.use': 'immediate',
				'mail.transport.use': 'mock'
			}

		log.info("Testing configuration: %r", dict(config))
		a = Mailer(config, 'mail')

		assert a.Manager == ImmediateManager
		assert a.Transport == MockTransport
Пример #16
0
 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')
Пример #17
0
def send_local_mail(user: str):
    mailer = Mailer(dict(transport=dict(use="sendmail", host="localhost")))
    mailer.start()

    otp = generate_otp_for_user(user)
    print(otp)

    message = Message(author="*****@*****.**", to=user)
    message.sendmail_f = "*****@*****.**"
    message.subject = "Login for Twit"
    message.plain = f"Your OTP is {otp}"
    mailer.send(message)

    mailer.stop()
Пример #18
0
def send(subject, text, html, sender, recipient, cc=None, bcc=None):

    mailer = Mailer(dict(transport=dict(use='smtp', host='localhost')))

    mailer.start()

    message = Message(author=sender, to=recipient, cc=cc, bcc=bcc)

    message.subject = subject
    message.rich = html
    message.plain = text

    mailer.send(message)
    mailer.stop()
Пример #19
0
def configured_mailer():
    config = {
        'transport.debug': True,
        'transport.timeout': 1,
        'transport.use': 'smtp',
        'transport.host': 'smtp.exmail.qq.com',
        'transport.port': 465,
        'transport.tls': 'ssl',
        'transport.username': admin_mail,
        'transport.password': secret.mail_password,
    }
    m = Mailer(config)
    m.start()
    return m
Пример #20
0
	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()
Пример #21
0
def configured_mailer():
    config = {
        # 'manager.use': 'futures',
        'transport.debug': True,
        'transport.timeout': 1,
        'transport.use': 'smtp',
        'transport.host': 'smtp.fengfan620.com',
        'transport.port': 465,
        'transport.tls': 'ssl',
        'transport.username': admin_mail,
        'transport.password': secret.mail_password,
    }
    m = Mailer(config)
    m.start()
    return m
Пример #22
0
 def test_use_deprecation(self):
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         
         Mailer(dict(manager='immediate', transport='mock'))
         
         self.assertEqual(len(w), 2, "Too few or too many warnings issued.")
         
         self.assertTrue(issubclass(w[0].category, DeprecationWarning), "Category of warning is not DeprecationWarning.")
         self.assertTrue('deprecated' in str(w[0].message), "Warning does not include 'deprecated'.")
         self.assertTrue('manager.use' in str(w[0].message), "Warning does not include correct use.")
         
         self.assertTrue(issubclass(w[1].category, DeprecationWarning), "Category of warning is not DeprecationWarning.")
         self.assertTrue('deprecated' in str(w[1].message), "Warning does not include 'deprecated'.")
         self.assertTrue('transport.use' in str(w[1].message), "Warning does not include correct use.")
Пример #23
0
    def command(self):
        "command"
        self.init()
        if self.options.email is None:
            print "\nA valid email is required\n"
            print self.parser.print_help()
            sys.exit(2)

        starttime = arrow.utcnow()

        if self.options.report_period == 'daily':
            endtime = starttime - datetime.timedelta(days=1)
        elif self.options.report_period == 'weekly':
            endtime = starttime - datetime.timedelta(weeks=1)
        else:
            endtime = starttime - datetime.timedelta(weeks=4)

        params = dict(spamscore=self.options.spamscore,
                      num=self.options.num,
                      starttime=starttime.datetime,
                      endtime=endtime.datetime)

        sql = text("""SELECT clientip, COUNT(clientip) a
                    FROM messages WHERE sascore <= :spamscore
                    AND (timestamp BETWEEN :endtime AND :starttime)
                    GROUP BY clientip HAVING COUNT(clientip) >= :num
                    ORDER BY a DESC;""")
        results = Session.execute(sql, params=params)
        if results.rowcount:
            if self.options.include_count is False:
                records = [result.clientip for result in results]
            else:
                records = ["%s\t%d" % tuple(result) for result in results]
            content = "\n".join(records)
            if self.options.dry_run is True:
                print content
            else:
                mailer = Mailer(get_conf_options(self.conf))
                mailer.start()
                email = Msg(author=self.conf['baruwa.reports.sender'],
                            to=self.options.email,
                            subject='TWL')
                email.plain = content
                try:
                    mailer.send(email)
                except (TransportFailedException, MessageFailedException), err:
                    print >> sys.stderr, err
                mailer.stop()
Пример #24
0
def configured_mail():
    config = {
        # 'manager.use': 'futures',
        'transport.use': 'smtp',
        'transprt.debug': True,
        'transprt.timeout': 1,
        'transport.host': 'smtp.gmail.com',
        'transport.port': 465,
        'transport.tls': 'ssl',
        'transport.username': secret.username,
        'transport.password': secret.password,
        'transport.max_messages_per_connection': 5
    }
    m = Mailer(config)
    m.start()
    return m
Пример #25
0
	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()
Пример #26
0
 def test_startup(self):
     messages = logging.getLogger().handlers[0].buffer
     
     interface = Mailer(base_config)
     interface.start()
     
     self.assertEqual(len(messages), 5)
     self.assertEqual(messages[0].getMessage(), "Mail delivery service starting.")
     self.assertEqual(messages[-1].getMessage(), "Mail delivery service started.")
     
     interface.start()
     
     self.assertEqual(len(messages), 6)
     self.assertEqual(messages[-1].getMessage(), "Attempt made to start an already running Mailer service.")
     
     interface.stop()
Пример #27
0
 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': {}
     })
Пример #28
0
def send_mail(subj, body, bifogad_fil, recipients=[], sender='*****@*****.**'):
    from marrow.mailer import Mailer, Message
    """Send mail to specified recipients."""
    recipients = [*recipients]
    mailer = Mailer(dict(
        transport=dict(use='smtp',
                       host='change.me.se')))

    mailer.start()
    message = Message(
        subject=f'{subj}',
        plain=f'{body}',
        author=sender,
        to=recipients,)
    message.attach(str(bifogad_fil))
    mailer.send(message)
    mailer.stop()
Пример #29
0
 def test_shutdown(self):
     interface = Mailer(base_config)
     interface.start()
     
     logging.getLogger().handlers[0].truncate()
     messages = logging.getLogger().handlers[0].buffer
     
     interface.stop()
     
     self.assertEqual(len(messages), 5)
     self.assertEqual(messages[0].getMessage(), "Mail delivery service stopping.")
     self.assertEqual(messages[-1].getMessage(), "Mail delivery service stopped.")
     
     interface.stop()
     
     self.assertEqual(len(messages), 6)
     self.assertEqual(messages[-1].getMessage(), "Attempt made to stop an already stopped Mailer service.")
Пример #30
0
    def __init__(self):
        from brave.mumble import util

        # Configure mail delivery services.
        util.mail = Mailer(config, 'mail')
        util.mail.start()

        # Load our keys into a usable form.
        config['api.private'] = SigningKey.from_string(unhexlify(
            config['api.private']),
                                                       curve=NIST256p,
                                                       hashfunc=sha256)
        config['api.public'] = VerifyingKey.from_string(unhexlify(
            config['api.public']),
                                                        curve=NIST256p,
                                                        hashfunc=sha256)

        super(StartupMixIn, self).__init__()