Пример #1
0
def send_mail(to: Union[List, AnyStr],
              template: AnyStr = "",
              data: Dict = None,
              pdf: ByteString = None,
              pdf_name="sample.pdf") -> None:
    """
    This function is used to send an email via Flask-Mail extension.
    :param to: recipients in form of string or list
    :param template: template name
    :param data: data used to render the template in form of dict
    :param pdf: pdf data in form of byte string
    :param pdf_name: name of pdf in form of string
    """

    if not template:
        raise ValueError(ErrorMessage.TEMPLATE_REQUIRED)

    subject = TEMPLATE_SUBJECTS.get(template)
    msg = Message(subject=subject,
                  recipients=[to] if isinstance(to, str) else to)

    try:
        template = render_template(f"email_templates/{template}.html",
                                   data=data)
        msg.html = template
    except TemplateNotFound as err:
        logger.error(ErrorMessage.TEMPLATE_404.format(err))
        raise ValueError(ErrorMessage.GENERIC_ERROR)

    if pdf:
        msg.attach(filename=pdf_name, content_type="application/pdf", data=pdf)

    mailer.send(msg)
    logger.info("Mail Send Successfully")
Пример #2
0
def send_phish_check_notice(destination: str \
, phishing_mails: List[PhishingEmail]) -> None:
    logger.info("Entering send_phish_check_notice")
    msg = Message("Piscator: Phishing Check Completed for {} on {}" \
    .format(destination, datetime.now().strftime("%d-%m-%Y, %H:%M"))\
    , recipients = [destination])

    msg.body = "A phishing check was executed on {}\n" \
    .format(destination)

    if len(phishing_mails) >= 1:
        msg.body += "These are the phishing emails detected - \n\n"

        for phish_mail in phishing_mails:
            msg.body += phish_mail.__repr__() + '\n\n'
    else:
        msg.body += "No phishing emails detected, congratulations!\n\n"

    msg.body +="This is an automated email sent from Project Piscator. "\
    "If you are not the intended recipient, please contact the administrative "\
    "team immediately.\n\nYou have received this mail because you have manually "\
    "started a phishing email check. For more detailed information, please login "\
    "to your dashboard on Project Piscator."

    mailer.send(msg)
    logger.info("Manual phish check notice sent.")
Пример #3
0
def contact():
  aForm = Contact()

  if aForm.validate_on_submit():
    # Check if the email provided is a valid one.
    aSubject = "Inquiry from {0}"
    aBody = "From {0} ({1})\n\n{2}"

    # Create the email.
    aMsg = Message(
      aSubject.format(aForm.name.data),
      sender=(aForm.name.data, aForm.email.data),
      recipients=["*****@*****.**"]
    )

    # Prepare the body.
    aMsg.body = aBody.format(aForm.name.data, aForm.email.data, aForm.message.data)

    # Send the email.
    mailer.send(aMsg)

    flash("Message sent!", "success")

    return redirect(url_for("personal.contact"))

  return render_template("personal/contact.html", theForm=aForm)
Пример #4
0
def send_daily_notice() -> None:
    logger.info("Routine task: sending daily notice to all active mailboxes")

    all_active_mailboxes = db.session.query(EmailAddress)\
    .filter(EmailAddress.active == True\
    , EmailAddress.notification_preference == True).all()

    for mailbox in all_active_mailboxes:
        logger.info("Checking through %s if any phishing emails detected today.."\
        , mailbox.get_email_address())

        phishing_mail_detected_today = db.session.query(PhishingEmail)\
        .filter(PhishingEmail.receiver_id == mailbox.get_email_id()\
        , (cast(PhishingEmail.created_at, Date)) == date.today()).all()

        if phishing_mail_detected_today:
            logger.info("Populating message content with mails detected today [%s]"\
            " for %s..", date.today().strftime('%d/%m/%y')\
            , mailbox.get_email_address())

            msg = Message("Piscator: Daily Update on your mailbox {}"\
            .format(mailbox.get_email_address()) \
            , recipients =[mailbox.get_email_address()])

            msg.body = "Hi, this is your daily update from Project Piscator.\n\n"\
            " We have detected the following possible phishing emails in your inbox:\n\n"

            for mail_detected in phishing_mail_detected_today:
                msg.body += mail_detected.__repr__() + '\n\n'
            mailer.send(msg)
            logger.info("Daily notice email sent for %s"\
            , mailbox.get_email_address())
        else:
            logger.info("No phishing emails detected today [%s] for %s"\
            , date.today().strftime('%d/%m/%y'), mailbox.get_email_address())
Пример #5
0
def send_phish_check_notice_context(destination: str \
, phishing_mails: List[PhishingEmail], app):
    with app.app_context():
        logger.info("Entering send_phish_check_notice_context")
        msg = Message("Piscator: Phishing Check Completed for {} on {}" \
        .format(destination, datetime.now().strftime("%d-%m-%Y, %H:%M"))\
        , recipients = [destination])

        msg.body = "An automatic phishing check was executed on {}\n" \
        .format(destination)

        if len(phishing_mails) >= 1:
            msg.body += "These are the phishing emails detected - \n\n"

            for phish_mail in phishing_mails:
                msg.body += phish_mail.__repr__() + '\n\n'

        msg.body +="This is an automated email sent from Project Piscator. "\
        "If you are not the intended recipient, please contact the administrative "\
        "team immediately.\n\nYou have received this mail because an automated "\
        "scan have detected potential phishing emails in your mailbox since the "\
        "last update. For more detailed information, please login "\
        "to your dashboard on Project Piscator."

        mailer.send(msg)
        logger.info("Automated phish check notice sent.")
Пример #6
0
def send_mail(subject, member, content):
    msg = Message(subject,
                  body='Hi {},\n\n{}'.format(member.en_name, content),
                  html=render_template('email.html',
                                       to_name=member.en_name,
                                       content=content),
                  recipients=[member.email])
    mailer.send(msg)
Пример #7
0
def send_contact_us_email(email: str, msg_body: str) -> None:
    logger.info("Entering send_contact_us_email")
    msg = Message("Mail from {}".format(email) \
    , recipients=['*****@*****.**'])
    msg.body = "Message from: {}\nDate sent:{}\nContent:{}".format(
    email, datetime.now(), msg_body)
    mailer.send(msg)
    logger.info("Email sent")
Пример #8
0
def send_email(user, subject, msg):
    if not user.email:
        return
    try:
        print(msg)
        mailer.send(
            subject, html_content=msg,
            from_email=settings.MAILER_SENDER,
            to=user.email
        )
    except:
        pass
Пример #9
0
def send_password_token(destination: str, username: str, token: str) -> None:
    logger.info("Entering send_password_token")
    msg = Message("You have recently requested a password reset for your account"\
    " on Project Piscator.", recipients=[destination])

    msg.body = "Hi {}, you have recently requested a password reset for your "\
    "account on Project Piscator.\nThe token generated for your password reset "\
    "is {}. This token will be valid for 1 hour(s)\n If you did not request for "\
    "this password reset, please contact the administrative team immediately.\n"\
    .format(username, token)
    mailer.send(msg)
    logger.info("Password reset token email sent")
Пример #10
0
def signup_alert(mcuser,
                 mcemail,
                 applicant_age,
                 applicant_skills,
                 applicant_ip,
                 fishbanned,
                 tb):
    msg = Message(
        "Signup Alert", sender=(
            app.config.get('MAIL_USER'), app.config.get('MAIL_USER')),
        recipients=ADMINS)
    msg.body = render_template("signupalert_email.txt",
                               mcuser=mcuser,
                               mcemail=mcemail,
                               applicant_age=applicant_age,
                               applicant_skills=applicant_skills,
                               applicant_ip=applicant_ip,
                               fishbanned=fishbanned,
                               tb=tb)
    mailer.send(msg)
Пример #11
0
def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    mailer.send(msg)
Пример #12
0
def send_mail(subject, sender, recipients, message_text, message_html,
              attachments):
    message = Message(subject, sender=sender, recipients=recipients)
    message = fill_message(message, message_text, message_html, attachments)

    mailer.send(message)
Пример #13
0
def send_mail_async(msg):
    """Non-blocking mail sender."""
    with app.app_context():
        mailer.send(msg)