Search code examples
pythonjinja2zabbix

Sending a Jinja2 templated email doesn't use new lines


My script accepts a variable from a Zabbix trigger (alert media). I'm trying to send that variable as an email but I don't see new lines in the email.

The original output has ^M at the end of each line, so I replace them with /n and then send that to be rendered in my Jinja2 template:

alert_message = sys.argv[1] # This is the variable I get from Zabbix
alert_message = alert_message.replace('\r', '\n')
f = open("/tmp/test.txt", "w") # I wrote the file to an output to see how it looks in raw text
f.write(alert_message)
f.close()
hostname = findGW(alert_message) # a function that uses regex to find the name of the hostname in the message
username = getOwner(hostname) # a function that gets the owner of the hostname to send him an email later
if username is not None:
    sendEmail(username, gw, alert_message) # Sending the email
else:
    print("Couldn't find gateway\nSkipping email sending")

This is my sendEmail() function:

def sendEmail(username, hostname, alert_msg):
    msg = MIMEMultipart('alternative')
    title = f'Instance alert for {hostname}'
    cc = ['email@email.com']
    # owner_email = [f'{username}@email.com']
    owner_email = [f'user@email.com']
    sender = 'alert@email.com'
    rendered_template = MIMEText(email_template.render({'owner':username, 'hostname':hostname, 'alert_msg':alert_msg}), 'html')
    msg['Subject'] = title
    msg['From'] = sender
    msg['Cc'] = ', '.join(cc)
    msg['To'] = ', '.join(owner_email)
    receivers = owner_email + cc
    msg.attach(rendered_template)
    try:
        smtpObj = smtplib.SMTP('mailserver', 25)
        smtpObj.sendmail(sender, receivers, msg.as_string())
        print ("Successfully sent email")
        smtpObj.quit()
    except Exception as e:
        print (e, "Error: unable to send email")

This is my HTML template which I render:

<p>Owner: {{owner}}, VM: <strong>({{hostname}})</strong>.
<br>
<b>Issue Message:</b>
{{alert_msg}}
<br>

For some reason, this is the email:

enter image description here

Just to compare, I also write the file as an output, and it looks like this, which would suggest everything is working properly:

enter image description here

Given the above comparison I'm not sure where to look for the issue. Is it Jinja2 or my script?


Solution

  • Just wanted to post an update. Not sure if this will help anyone since this is a pretty janky solution, but overall:

    I get the message from Zabbix, parse it in my script, and send it in a templated email using Jinja.

    The fuction:

    def parseMessage(message):
        d = {}
        for line in message.splitlines():
            if line.startswith("Problem name:"):
                problemMessage = line.split(":")[1].strip()
                d['Problem name'] = problemMessage
            
            if line.startswith("Problem started") or line.startswith("Problem has been resolved"):
                d['Start Time'] = line
    
            if line.startswith("Severity"):
                d['Severity'] = line.split(":")[1].strip()
    
            if line.startswith("Host:"):
                d['hostname'] = line.split(":")[1].strip()
        return d
    

    Then the template looks something like this:

    <p>bla bla bla
    <br>
    {% if "Problem has been resolved" in issue_time %}
    <p>
        This is an update to the previous email you received.
        bla bla bla
    </p>
    {% endif %}
    <ul>
        <li>
            Issue Message: {{issue_message}}
        </li>
        <li>
            Issue Time: {{issue_time}}
        </li>
        <li>
            Issue Severity: {{issue_sev}}
        </li>
    </ul>
    <br>