Add options to send report by email

This commit is contained in:
Alfredo Cardigliano 2023-01-27 15:30:26 +01:00
parent bc172e46d5
commit aec30eb28e

View file

@ -8,10 +8,10 @@ import os
import sys
import time
import getopt
import pandas as pd
from fpdf import FPDF
import plotly.figure_factory as ff
import plotly.graph_objects as go
from redmail import EmailSender
from pathlib import Path
from getpass import getpass
sys.path.insert(0, '../../')
@ -27,14 +27,22 @@ auth_token = None
enable_debug = False
output_file = "report.pdf"
actual_ts = int(time.time())
yesterday = (actual_ts - 86400)
### SMTP server configuration
smtp_host = "mail.example.org"
smtp_port = 25
smtp_username = "sender"
smtp_password = None
### Email sender/recipient
email_sender = "sender@example.org"
email_recipient = None
email_subject = "New report"
##########
def usage():
print("test.py [-u <username>] [-p <password>] [-t <auth token>] [-n <ntopng_url>]")
print(" [-i <interface ID>] [--debug] [--help]")
print(" [-i <interface ID>] [-r <email recipient>] [--debug] [--help]")
print("")
print("Example: ./test.py -t ce0e284c774fac5a3e981152d325cfae -i 4")
print(" ./test.py -u ntop -p mypassword -i 4")
@ -44,13 +52,14 @@ def usage():
try:
opts, args = getopt.getopt(sys.argv[1:],
"hdu:p:n:i:t:",
"hdu:p:n:i:r:t:",
["help",
"debug",
"username=",
"password=",
"ntopng_url=",
"iface_id=",
"recipient=",
"auth_token="]
)
except getopt.GetoptError as err:
@ -71,6 +80,8 @@ for o, v in opts:
ntopng_url = v
elif(o in ("-i", "--iface_id")):
iface_id = v
elif(o in ("-r", "--recipient")):
email_recipient = v
elif(o in ("-t", "--auth_token")):
auth_token = v
@ -91,8 +102,35 @@ except ValueError as e:
generator = Report(my_ntopng, iface_id)
print("Generating PDF...")
print("Generating PDF " + output_file + "...")
generator.generate_interface_report(output_file)
if email_recipient is not None:
print("Sending report " + output_file + " by email...")
if smtp_host is None:
print("Please set the SMTP server parameters in the settings section")
os._exit(-1)
if smtp_password is None:
print("Please enter the password for " + smtp_username)
smtp_password = getpass()
email = EmailSender(
host = smtp_host,
port = smtp_port,
username = smtp_username,
password = smtp_password
)
email.send(
sender = email_sender,
receivers = [email_recipient],
subject = email_subject,
attachments = {
"report.pdf": Path(output_file)
}
)