# Alert script notification (Enterprise) to e-mail not working

**URL:** <https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214>\
**Category:** Graylog Central (peer support)\
**Tags:** alert, python\
**Created:** [August 9, 2022, 9:06pm UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214 "2022-08-09T21:06:35Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tmacgbay](https://sea2.discourse-cdn.com/flex016/user_avatar/community.graylog.org/tmacgbay/32/3878_2.png) [@tmacgbay](https://community.graylog.org/u/tmacgbay)\
**Post date:** [August 9, 2022, 9:06pm UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214/1 "2022-08-09T21:06:35Z")

</div>

I am trying to put together a Alert Python script Notification and I have not had much luck at all. I am basing my script from a [previous post on how to do it](https://community.graylog.org/t/send-email-alert-by-script-deriving-recipient-from-message-field/22438) from @Elix but it’s not working. Maybe YOU can look at it and help me to figure out what I am doing wrong?

I know the alert fires off and other notifications can send e-mail… its really that the script fails silently. Here is the script:

```auto
#!/usr/bin/env python3

import getopt
import graypy
import logging
import smtplib
import sys

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

gelf_logger = 0

def body_html(evnt_fields):

    try:
        rv = f"""\
       <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Password Lockout</title>

                </head>

                <body>
                <table width="100%" cellpadding="10" cellspacing="0" style="background-color:#f9f9f9;line-height:1">
                   <tbody>
                    <!-- Event Digest Title Bar -->
                        <th colspan="3" style="background-color:#e6e6e6;line-height:1.5">
                                 - Event Digest - {evnt_fields['timestamp']} - <br> 
                                ACCOUNT LOCKED - <br>
                        </th>
                      <!-- First section quick info/digest on alert -->
                    <tr>
                            <td>Locked Account:</td>
                            <td>{evnt_fields['winlog_event_data_TargetUserName']}</td>
                    </tr>
                    <tr>
                            <td>Locked From:</td>
                            <td>{evnt_fields['winlog_event_data_TargetDomainName']}</td>
                    </tr>
                    <tr>
                            <td>NOTE:</td>
                            <td>The IT Group has been notified that {evnt_fields['winlog_event_data_TargetUserName']} has been locked out. <br>
                                For immediate assistance you can call the IT Group at #### or e-mail us at email@email.com
                            </td>
                    </tr>
                   </tbody>
                </table>
            </body>
        </html>"""
        
    except KeyError:
        gelf_logger.debug("Exception KeyError in body_html()", exc_info=1)
        sys.exit(10)

    return rv

def body_plain(evnt_fields):
    try:
        rv = f"""
           --------------------------------------------------------------------------------------------------------------------------
                The following account has been locked out: {evnt_fields['winlog_event_data_TargetUserName']}
            --------------------------------------------------------------------------------------------------------------------------

                    Account locked out : {evnt_fields['winlog_event_data_TargetUserName']}
                    Locked from Server : {evnt_fields['winlog_event_data_TargetDomainName']}

                    NOTE: The IT Group has been notified that {evnt_fields['winlog_event_data_TargetUserName']} has been locked out.
                    
                        For immediate assistance you can call the IT Group at ####### 
                        alternatively, e-mail us at email@email.com

                   Timestamp: {evnt_fields['event_created']}

            --------------------------------------------------------------------------------------------------------------------------

"""
    except KeyError:
        gelf_logger.debug("Exception KeyError in body_plain()", exc_info=1)
        sys.exit(11)

    return rv

def init_logging():
    global gelf_logger
    handler = graypy.GELFTCPHandler("MyGraylogServer", 12202)
    gelf_logger = logging.getLogger("Log_to_Graylog")
    gelf_logger.setLevel(logging.DEBUG)
    gelf_logger.addHandler(handler)

def parse_cmdline_params(argv):
    longopts = ['winlog_event_data_TargetUserName=',
                'winlog_event_data_TargetDomainName=',
                'user_email=',
                'event_created=']
    argvc = []
    for arg in argv:
        argvc.append(arg.replace("\"", ""))
    try:
        opts, args = getopt.getopt(args=argvc,
                                   shortopts="",
                                   longopts=longopts)
    except getopt.GetoptError:
        gelf_logger("Exception getopt.Getopt in parse_cmdline_params()", exc_info=1)
        sys.exit(12)

    rv = {}
    for opt, arg in opts:
        rv.setdefault(opt[2:], arg)
    return rv

def trigger_email(evnt_fields, relay="mailgateway"):
    try:
        subject = f"ACOUNT LOCKED: {evnt_fields['winlog_event_data_TargetUserName']} from server {evnt_fields['winlog_event_data_TargetDomainName']}"
        msgfrom = "awesomeIT@email.com"
        msgrcpt = f"{evnt_fields['user_email']}"

    except KeyError:
        gelf_logger.debug("Exception KeyError in trigger_email()", exc_info=1)
        sys.exit(13)

    msg = MIMEMultipart("alternative")
    msg['Subject'] = subject
    msg['From'] = msgfrom
    msg['To'] = msgrcpt
    msg.attach(MIMEText(body_plain(evnt_fields), "plain"))
    msg.attach(MIMEText(body_html(evnt_fields), "html"))

    try:
        with smtplib.SMTP(relay) as srv:
            srv.send_message(msg)
    except Exception:
        gelf_logger.debug("Exception in trigger_email()", exc_info=1)
        sys.exit(14)

    return subject, msgrcpt

def main(argv):
    init_logging()
    evnt_fields = parse_cmdline_params(argv)
    subject, msgrcpt = trigger_email(evnt_fields)
    gelf_logger.debug(f"Sucessfully sent email alert with subject {subject} to {msgrcpt}.")
    sys.exit(0)

if __name__ == " __main__":
    main(sys.argv[1:])

```

and here is how the script is implemented:

 ![image](https://us1.discourse-cdn.com/flex016/uploads/graylog/original/2X/4/4347bf52affcec396035d9c57276accfd86234cc.png)

I tried following the previous post as close as possible - I even have messier code similar to the above that I can get to run manually with python3 but as soon as I put it into Graylog it chokes.

Its likely something like flip that bit over there… just can’t find that bit. 😃

---

<div class="post-metadata">

**Author:** ![gsmith](https://sea2.discourse-cdn.com/flex016/user_avatar/community.graylog.org/gsmith/32/1222_2.png) [@gsmith](https://community.graylog.org/u/gsmith)\
**Post date:** [August 9, 2022, 11:40pm UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214/2 "2022-08-09T23:40:39Z")

</div>

@tmacgbay  
Question, I’m labbing this sup , where it states **Script path** where do you drop the py script? Sorry first time using Enterprise stuff.

EDIT: 😆 nvm

---

<div class="post-metadata">

**Author:** ![Elix](https://avatars.discourse-cdn.com/v4/letter/e/e19adc/32.png) [@Elix](https://community.graylog.org/u/Elix)\
**Post date:** [August 11, 2022, 9:04am UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214/3 "2022-08-11T09:04:09Z")

</div>

Hi tmacgbay,

about the Script Arguments: Can you try again without dashes and untick the option to send alert data through STDIN?

---

<div class="post-metadata">

**Author:** ![tmacgbay](https://sea2.discourse-cdn.com/flex016/user_avatar/community.graylog.org/tmacgbay/32/3878_2.png) [@tmacgbay](https://community.graylog.org/u/tmacgbay)\
**Post date:** [August 12, 2022, 3:33pm UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214/4 "2022-08-12T15:33:28Z")

</div>

No luck so far… still puttering with it… The good news is the GELF logging is working! Here is the error I see:

```auto
full_message
Traceback (most recent call last):

  File "/etc/graylog/scripts/alert-user-pw-fail.py", line 117, in trigger_email
    subject = f"ACOUNT LOCKED: {evnt_fields['winlog_event_data_TargetUserName']} from server {evnt_fields['winlog_event_data_TargetDomainName']}"

KeyError: 'winlog_event_data_TargetUserName'

```

Definitely an issue with how I am passing in parameters, More research needed as to how Python wants them to come in… and how Graylog presents them to the scripts… :-\

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex016/uploads/graylog/original/3X/c/7/c7c09c6b5099570133d6502b83f50ba4430de5b6.png) [@system](https://community.graylog.org/u/system)\
**Post date:** [August 26, 2022, 3:34pm UTC](https://community.graylog.org/t/alert-script-notification-enterprise-to-e-mail-not-working/25214/5 "2022-08-26T15:34:27Z")

</div>

Closed on August 26, 2022, 3:34pm UTC

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
