Skip to content

Commit 0278e1c

Browse files
committed
bug fix and support ssl, tls, no encryption
1 parent 24cc340 commit 0278e1c

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

functions/net/tcp/email/alterscript_msmtp_public.py

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import string
1515
import sys
1616

17+
import six
18+
1719

1820
def usage():
1921
print("""
@@ -23,17 +25,25 @@ def usage():
2325
https://hostname/zabbix.php?action=mediatype.edit&mediatypeid=4
2426
Script parameters: {ALERT.SENDTO} {ALERT.SUBJECT} {ALERT.MESSAGE}
2527
Example: python %s "admin@example.domain" "Test email from Python" "Python rules them all!"
26-
""") % (__file__, sys.argv[0])
28+
""" % (__file__, sys.argv[0]))
2729
sys.exit(0)
2830

2931

3032
EMAIL_HOST = "smtp.example.domain" # change it
3133
EMAIL_PORT = 25 # default smtp port
34+
EMAIL_HOST_ENABLE_SSL = False # the most frequently used option
35+
EMAIL_HOST_ENABLE_TLS = False # not all smtp server support TLS
3236
EMAIL_HOST_USER = 'noreply@example.domain' # change it
3337
EMAIL_HOST_PASSWORD = 'your password' # change it
3438
DEFAULT_FROM_EMAIL = 'noreply@example.domain' # change it, https://tools.ietf.org/html/rfc822.html#appendix-A
3539
CRLF = "\r\n" # for Windows user read easily
3640

41+
if EMAIL_HOST_ENABLE_SSL and EMAIL_HOST_ENABLE_TLS:
42+
raise Exception("can NOT be used together")
43+
44+
if EMAIL_HOST_ENABLE_SSL:
45+
EMAIL_PORT = 465
46+
3747
# user defined variable, in Zabbix is {ALERT.SENDTO}
3848
EMAIL_TO = "example@example.domain"
3949
# user defined variable, in Zabbix is {ALERT.SUBJECT}
@@ -53,17 +63,37 @@ def usage():
5363
EMAIL_SUBJECT = sys.argv[2]
5464
EMAIL_BODY = sys.argv[3]
5565

56-
BODY = string.join((
57-
"From: %s" % DEFAULT_FROM_EMAIL,
58-
"To: %s" % EMAIL_TO,
59-
"Subject: %s" % EMAIL_SUBJECT,
60-
"",
61-
EMAIL_BODY
62-
), CRLF)
66+
if six.PY2:
67+
BODY = string.join((
68+
"From: %s" % DEFAULT_FROM_EMAIL,
69+
"To: %s" % EMAIL_TO,
70+
"Subject: %s" % EMAIL_SUBJECT,
71+
"",
72+
EMAIL_BODY
73+
), CRLF)
74+
else:
75+
BODY = CRLF.join((
76+
"From: %s" % DEFAULT_FROM_EMAIL,
77+
"To: %s" % EMAIL_TO,
78+
"Subject: %s" % EMAIL_SUBJECT,
79+
"",
80+
EMAIL_BODY
81+
))
82+
83+
if EMAIL_HOST_ENABLE_SSL or EMAIL_HOST_ENABLE_TLS:
84+
if six.PY3:
85+
# for python3, ValueError: server_hostname cannot be an empty string or start with a leading dot.
86+
server = smtplib.SMTP_SSL(host=EMAIL_HOST)
87+
else:
88+
server = smtplib.SMTP_SSL()
89+
else:
90+
server = smtplib.SMTP()
6391

64-
server = smtplib.SMTP()
6592
server.connect(EMAIL_HOST, EMAIL_PORT)
66-
server.starttls()
93+
94+
if EMAIL_HOST_ENABLE_TLS:
95+
server.starttls()
96+
6797
server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
6898
server.sendmail(DEFAULT_FROM_EMAIL, [EMAIL_TO], BODY)
6999
server.quit()

0 commit comments

Comments
 (0)