Skip to content

Commit

Permalink
Better mail notification defaults.
Browse files Browse the repository at this point in the history
  • Loading branch information
riga committed Jan 4, 2025
1 parent 319c64d commit b78dda9
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 12 deletions.
8 changes: 4 additions & 4 deletions law.cfg.example
Original file line number Diff line number Diff line change
Expand Up @@ -986,13 +986,13 @@

; mail_smtp_host
; Description: The SMTP host for notifications sent by "law.notification.notify_mail".
; Type: ``str``
; Default: ``"127.0.0.1"``
; Type: ``str``, ``None``
; Default: ``None``

; mail_smtp_port
; Description: The SMTP port for notifications sent by "law.notification.notify_mail".
; Type: ``int``
; Default: ``25``
; Type: ``int``, ``None``
; Default: ``None``


; --- Options of contrib packages
Expand Down
4 changes: 2 additions & 2 deletions law/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ def __str__(self) -> str:
"notifications": {
"mail_recipient": None,
"mail_sender": None,
"mail_smtp_host": "127.0.0.1",
"mail_smtp_port": 25,
"mail_smtp_host": None,
"mail_smtp_port": None,
},
"bash_sandbox": {
"stagein_dir_name": "stagein",
Expand Down
15 changes: 10 additions & 5 deletions law/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,26 @@ def notify_mail(
"""
cfg = Config.instance()

# get config recipient and sender values from config
if not recipient:
recipient = cfg.get_expanded("notifications", "mail_recipient")
if not sender:
sender = cfg.get_expanded("notifications", "mail_sender")
if not smtp_host:
smtp_host = cfg.get_expanded("notifications", "mail_smtp_host")
if not smtp_port:
smtp_port = cfg.get_expanded("notifications", "mail_smtp_port")

if not recipient or not sender:
logger.warning(
f"cannot send mail notification, recipient ({recipient}) or sender ({sender}) empty",
)
return False

# get host and port
if not smtp_port:
smtp_port = cfg.get_expanded("notifications", "mail_smtp_port")
if not smtp_host:
smtp_host = cfg.get_expanded("notifications", "mail_smtp_host")
# infer host from sender when not set
if not smtp_host:
smtp_host = sender.split("@", 1)[1]

mail_kwargs: dict[str, str | int] = {}
if smtp_host:
mail_kwargs["smtp_host"] = smtp_host
Expand Down
2 changes: 1 addition & 1 deletion law/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2124,7 +2124,7 @@ def send_mail(
try:
server = smtplib.SMTP(smtp_host, smtp_port)
except Exception as e:
logger.warning(f"cannot create SMTP server: {e}")
logger.warning(f"cannot create SMTP server {smtp_host}:{smtp_port}: {e}")
return False

header = f"From: {sender}\r\nTo: {recipient}\r\nSubject: {subject}\r\n\r\n"
Expand Down

0 comments on commit b78dda9

Please sign in to comment.