Exemple #1
0
def send_email(email_to: str, subject_template="", html_template="", environment=None) -> Union[SMTPResponse, bool]:
    if environment is None:
        environment = {}
    assert config.EMAILS_ENABLED, "no provided configuration for email variables"
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(config.EMAILS_FROM_NAME, config.EMAILS_FROM_EMAIL),
    )
    smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT}
    if config.SMTP_TLS:
        smtp_options["tls"] = True
    if config.SMTP_USER:
        smtp_options["user"] = config.SMTP_USER
    if config.SMTP_PASSWORD:
        smtp_options["password"] = config.SMTP_PASSWORD
    try:
        response = message.send(to=email_to, render=environment, smtp=smtp_options)
        assert response.status_code == 250
        logging.info(f"Send email result: {response}")
    except SMTPException as error:
        logging.error(f"Error while trying to send email: {error}")
        return False
    except AssertionError:
        logging.error(f"Failed to send email, send email result: {response}")
        return False
    return response
Exemple #2
0
def send_email(email_to: str,
               subject_template="",
               html_template="",
               environment={}):
    if not settings.EMAILS_ENABLED:
        if settings.EMAIL_TESTING:
            logging.info("\nMessage: " + subject_template + "\nSent to: " +
                         email_to)
            return

        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Emails not enabled.")

    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
    )
    smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
    if settings.SMTP_TLS:
        smtp_options["tls"] = True
    if settings.SMTP_USER:
        smtp_options["user"] = settings.SMTP_USER
    if settings.SMTP_PASSWORD:
        smtp_options["password"] = settings.SMTP_PASSWORD
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
Exemple #3
0
def send_email(
    email_to: str,
    subject_template: str = "",
    html_template: str = "",
    environment: Dict[str, Any] = {},
) -> None:
    assert current_app.config[
        "EMAILS_ENABLED"], "no provided configuration for email variables"
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(current_app.config["EMAILS_FROM_NAME"],
                   current_app.config["EMAILS_FROM_EMAIL"]),
    )
    smtp_options = {
        "host": current_app.config["MAIL_SERVER"],
        "port": current_app.config["MAIL_PORT"]
    }
    if current_app.config["MAIL_USE_TLS"]:
        smtp_options["tls"] = True
    if current_app.config["MAIL_USERNAME"]:
        smtp_options["user"] = current_app.config["MAIL_USERNAME"]
    if current_app.config["MAIL_PASSWORD"]:
        smtp_options["password"] = current_app.config["MAIL_PASSWORD"]
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
Exemple #4
0
def send_email(
    email_to: str,
    subject_template: str = "",
    html_template: str = "",
    environment: Dict[str, Any] = {},
) -> None:

    assert settings.EMAILS_ENABLED, "no provided configuration for email variables"
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
    )
    smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
    if settings.SMTP_TLS:
        smtp_options["tls"] = True
    if settings.SMTP_SSL:
        smtp_options["ssl"] = True
    if settings.SMTP_USER:
        smtp_options["user"] = settings.SMTP_USER
    if settings.SMTP_PASSWORD:
        smtp_options["password"] = settings.SMTP_PASSWORD
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    print(response)
    logging.info(f"send email result: {response}")
Exemple #5
0
def send_email(email_to: str,
               subject_template: str = "",
               html_template: str = "",
               environment: Dict[str, Any] = {}) -> None:
    message = emails.Message(subject=JinjaTemplate(subject_template),
                             html=JinjaTemplate(html_template),
                             mail_from=(None, None))
    smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT}
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
Exemple #6
0
def send_email(email_to: str, subject_template='', html_template='', context: dict = {}):
    assert settings.EMAILS_ENABLED, 'please configure email backend to send emails'

    message = emails.Message(subject=JinjaTemplate(subject_template),
                             html=JinjaTemplate(html_template),
                             mail_from=(settings.EMAIL_FROM_NAME, settings.EMAIL_FROM_EMAIL))
    smtp_options = {'host': settings.SMTP_HOST,
                    'port': settings.SMTP_PORT,
                    'user': settings.EMAIL_HOST_USER,
                    'password': settings.EMAIL_HOST_PASSWORD}
    if settings.SMTP_TLS:
        smtp_options['tls'] = True

    message.send(email_to, render=context, smtp=smtp_options)
def render_email_template(results):
    """Return populated text that can be sent as an email summary of the item/location results.

    Inputs:
        results (dict) --  Two-dimensional dictionary containing search keywords (keys) and location search results (key, value pairs).

    Returns:
        str -- Summary of results in HTML format.
    """
    with open(
            'ebay_multilocation_item_notifier/templates/notification-email.html'
    ) as fp:
        template = JinjaTemplate(fp.read())

    return template.render(results=results)
Exemple #8
0
def send_email(email_to: str, subject_template="", html_template="", environment={}):
    assert config.EMAILS_ENABLED, "no provided configuration for email variables"
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(config.EMAILS_FROM_NAME, config.EMAILS_FROM_EMAIL),
    )
    smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT}
    if config.SMTP_TLS:
        smtp_options["tls"] = True
    if config.SMTP_USER:
        smtp_options["user"] = config.SMTP_USER
    if config.SMTP_PASSWORD:
        smtp_options["password"] = config.SMTP_PASSWORD
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
def test_render_message_with_template():
    TEMPLATE = JinjaTemplate('Hello, {{name}}!')
    V = dict(name='world')
    RESULT = TEMPLATE.render(**V)
    assert RESULT == 'Hello, world!'

    msg = emails.html(subject=TEMPLATE)
    msg.render(**V)
    assert msg.subject == RESULT

    msg = emails.html(html=TEMPLATE)
    msg.render(**V)
    assert msg.html_body == RESULT

    msg = emails.html(text=TEMPLATE)
    msg.render(**V)
    assert msg.text_body == RESULT
Exemple #10
0
def _build_message() -> Message:
    with _EMAIL_TEMPLATE.open("r") as _:
        template = _.read()
    return emails.html(
        subject=params.email.subject,
        mail_from=str(params.email.sender),
        html=JinjaTemplate(template),
    )
Exemple #11
0
def send_email(email_to: str,
               subject_template: str = "",
               html_template: str = "",
               environment: Dict[str, Any] = {}) -> None:
    assert settings.EMAIL_ENABLED, "no provided configuration for email variables"
    message = emails.Message(subject=JinjaTemplate(subject_template),
                             html=JinjaTemplate(html_template),
                             mail_from=(settings.EMAIL_FROM_NAME,
                                        settings.EMAIL_FROM_ADDRESS))
    smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
    if settings.SMTP_TLS:
        smtp_options["tls"] = True
    if settings.SMTP_USER:
        smtp_options["user"] = settings.SMTP_USER
    if settings.SMTP_PASSWORD:
        smtp_options["password"] = settings.SMTP_PASSWORD
    message.send(to=email_to, render=environment, smtp=smtp_options)
    async def send_mail(self, to: str, subject: str = "", template: str = "", environment: Any = {}) -> None:

        """
        [Send]

        Метод, отвечающий за отправку сообщения по почте. Только и всего.
        """

        message = emails.Message(
            subject=JinjaTemplate(subject),
            html=JinjaTemplate(template),
            mail_from=("Untername0", email_config.DEFAULT_FROM_EMAIL))

        settings = {
            "host": email_config.EMAIL_HOST,
            "port": email_config.EMAIL_PORT,
            "user": email_config.EMAIL_HOST_USER,
            "password": email_config.EMAIL_HOST_PASSWORD,
            "tls": email_config.EMAIL_USE_TLS}

        response = message.send(to=to, render=environment, smtp=settings)
        assert response.status_code == 250
Exemple #13
0
def send_email(
    email_to: str,
    subject_template: str = "",
    html_template: str = "",
    text_template: str = "",
    environment: Dict[str, Any] = {},
) -> None:
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        text=JinjaTemplate(text_template),
        mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
    )
    smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
    if settings.SMTP_TLS:
        smtp_options["tls"] = True
    if settings.SMTP_USER:
        smtp_options["user"] = settings.SMTP_USER
    if settings.SMTP_PASSWORD:
        smtp_options["password"] = settings.SMTP_PASSWORD
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"send email result: {response}")
def test_templates_commons():
    JINJA_TEMPLATE = "Hello, {{name}}!"
    STRING_TEMPLATE = "Hello, $name!"
    MAKO_TEMPLATE = "Hello, ${name}!"
    RESULT = "Hello, world!"

    values = {'name': 'world'}

    assert JinjaTemplate(JINJA_TEMPLATE).render(**values) == RESULT

    assert StringTemplate(STRING_TEMPLATE).render(**values) == RESULT

    assert MakoTemplate(MAKO_TEMPLATE).render(**values) == RESULT
def send_email(
    email_to: str,
    subject_template: str = "",
    html_template: str = "",
    environment: Dict[str, Any] = {},
):

    # print(">>>  send_email > settings : ...")
    # pp.pprint(settings.dict())

    assert settings.EMAILS_ENABLED, "no provided configuration for email variables"

    with open(Path(f'{cwd}{settings.EMAIL_TEMPLATES_DIR}') /
              html_template) as f:
        template_str = f.read()

    subject = JinjaTemplate(subject_template)
    template = JinjaTemplate(template_str)
    # print(">>>  send_email > template : ...",  template)
    # print("send_email > email_to : ", email_to)
    # print("send_email > subject : ", subject)
    # print("send_email > settings.EMAILS_FROM_EMAIL : ", settings.EMAILS_FROM_EMAIL)
    # print("send_email > environment : ", environment)
    # print("send_email > subject_template : ", subject_template)
    # print("send_email > html_template : ", html_template)

    message = emails.Message(
        subject=subject,
        html=template,
        # mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
        mail_from=(settings.EMAILS_FROM_EMAIL),
    )
    print("send_email > message : ", message)

    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    print("send_email > response : ", response)
    logging.info(f"send email > result: {response}")
Exemple #16
0
def send_email(email_to: str,
               subject_template: str = "",
               html_template: str = "",
               environment: tp.Mapping = {}) -> None:
    """Sends an email with the given parameters.

    Parameters
    ----------
    email_to : str
        The email address to send the email to.
    subject_template : str, optional
        The subject line template string to use.
    html_template : str, optional
        The email body template string to use.
    environment : Mapping, optional
        The environment variables to use in rendering the message.

    """
    if not config.EMAILS_ENABLED:
        logging.warn("Emails are not enabled")
        return

    message = emails.Message(subject=JinjaTemplate(subject_template),
                             html=JinjaTemplate(html_template),
                             mail_from=(config.EMAILS_FROM_NAME,
                                        config.EMAILS_FROM_EMAIL))
    smtp_options = dict(host=config.SMTP_HOST, port=config.SMTP_PORT)
    if config.SMTP_TLS:
        smtp_options["tls"] = True
    if config.SMTP_USER:
        smtp_options["user"] = config.SMTP_USER
    if config.SMTP_PASSWORD:
        smtp_options["password"] = config.SMTP_PASSWORD
    response = message.send(to=email_to, render=environment, smtp=smtp_options)
    logging.info(f"Email send result: {response}")
    return
Exemple #17
0
def send_email(template, subject, data_map, recipient):
    template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "email_templates", template)

    smtp_config = {
        'host': CONFIG.smtp_host,
        'port': CONFIG.smtp_port,
        'user': CONFIG.smtp_user,
        'password': CONFIG.smtp_pass,
        'ssl': True
    }

    message = emails.Message(html=JinjaTemplate(open(template_path).read()), subject=subject, mail_from=("VulnFeed Agent", "*****@*****.**"))

    if CONFIG.has_dkim:
        message.dkim(key=open(CONFIG.dkim_privkey), domain=CONFIG.dkim_domain, selector=CONFIG.dkim_selector)


    response = message.send(render=data_map, to=recipient, smtp=smtp_config)

    return response
Exemple #18
0
        subject_template = ""
    elif isinstance(subject_template, Path):
        with open(subject_template, 'r') as fin:
            subject_template = fin.read()
    if html_template is None:
        html_template = ""
    elif isinstance(html_template, Path):
        with open(html_template, 'r') as fin:
            html_template = fin.read()
    environment = environment or {}
    if isinstance((attachments := attachments or {}), Path):
        attachments = {attachments.name: attachments}

    # - Construct message
    message = emails.Message(
        subject=JinjaTemplate(subject_template),
        html=JinjaTemplate(html_template),
        mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
    )
    for name, file in attachments.items():
        with open(file) as fin:
            message.attach(data=fin, filename=name)

    smtp_opts = {
        "host": settings.SMTP_HOST,
        "port": settings.SMTP_PORT,
    }
    if settings.SMTP_TLS:
        smtp_opts["tls"] = True
    if settings.SMTP_USER:
        smtp_opts["user"] = settings.SMTP_USER
Exemple #19
0
    def process_user(self, user_email):
        # Get object
        u = User(user_email)
        days_to_run = u.get_days()
        last_day = u.last_run
        current_time = datetime.utcnow()
        current_day = int(current_time.strftime("%w")) + 1
        day_diff = 2
        if last_day > 0:
            if last_day > current_day:
                current_day += 7
            day_diff = current_day - last_day
        
        
        # Get reports between the time requested plus some buffer time
        query_time = current_time - timedelta(hours=(day_diff*24)+4)
        reports = get_feed_reports(query_time)

        rules = u.get_rules()
        filled_rules = fill_rules(rules)

        report_map = {}

        for report in reports:
            self.check_report(report_map, report, filled_rules)


        high_reports = []
        medium_reports = []
        low_reports = []
        report_count = 0

        for report_id in report_map:
            score = report_map[report_id]['score']
            report = report_map[report_id]['report']
            report_count += 1
            if score == 0:
                low_reports.append(report)
            else:
                high_reports.append(report)

        render_map = {
            "vulncount": report_count,
            "high_importance_reports": high_reports,
            "medium_importance_reports": medium_reports,
            "low_importance_reports": low_reports
        }
        template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", 'email_template.html')

        smtp_config = {
            'host': CONFIG.smtp_host,
            'port': CONFIG.smtp_port,
            'user': CONFIG.smtp_user,
            'password': CONFIG.smtp_pass,
            'ssl': True
        }

        m = emails.Message(html=JinjaTemplate(open(template_path).read()),  text="hi there",  subject="VulnFeed Test", mail_from=("VulnFeed Agent", "*****@*****.**"))
        response = m.send(render=render_map, to=user_email, smtp={smtp_config)
        print(response)

    def run(self):

        for user_email in self.user_chunk:
            self.process_user(user_email)

sm = SenderMaster()
sm.start_senders()
Exemple #20
0
    def process_user(self, user_email):
        # Get object
        u = User(user_email)
        days_to_run = u.get_days()
        last_day = u.last_run
        current_time = datetime.utcnow()
        current_day = int(current_time.strftime("%w")) + 1

        if current_day not in days_to_run:
            return

        day_diff = 2
        if last_day > 0:
            if last_day > current_day:
                current_day += 7
            day_diff = current_day - last_day

        # Get reports between the time requested plus some buffer time
        query_time = current_time - timedelta(hours=(day_diff * 24) + 4)
        reports = get_feed_reports(query_time)

        rules = u.get_rules()
        filled_rules = fill_rules(rules)

        report_map = {}

        for report in reports:
            self.check_report(report_map, report, filled_rules)

        sorted_reports = sorted(report_map,
                                key=lambda item: report_map[item]['score'],
                                reverse=True)

        scored_reports = []
        unscored_reports = []

        for item in sorted_reports:
            if report_map[item]['score'] > 0:
                scored_reports.append(report_map[item]['report'])
            else:
                unscored_reports.append(report_map[item]['report'])

        for item in sorted_reports:
            print(report_map[item]['score'])
            print(report_map[item]['report']['contents'])

        report_count = len(sorted_reports)

        render_map = {
            "vulncount": report_count,
            "scored_reports": scored_reports,
            "unscored_reports": unscored_reports
        }
        template_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), "templates",
            'email_template.html')

        smtp_config = {
            'host': CONFIG.smtp_host,
            'port': CONFIG.smtp_port,
            'user': CONFIG.smtp_user,
            'password': CONFIG.smtp_pass,
            'ssl': True
        }

        m = emails.Message(html=JinjaTemplate(open(template_path).read()),
                           subject="VulnFeed Report for " +
                           time.strftime("%m/%d/%Y"),
                           mail_from=("VulnFeed Agent", "*****@*****.**"))
        response = m.send(render=render_map, to=user_email, smtp=smtp_config)
        print(response)