diff --git a/mail_client/mail_client/doctype/outgoing_mail/outgoing_mail.py b/mail_client/mail_client/doctype/outgoing_mail/outgoing_mail.py index dc4629a2..c03b212b 100644 --- a/mail_client/mail_client/doctype/outgoing_mail/outgoing_mail.py +++ b/mail_client/mail_client/doctype/outgoing_mail/outgoing_mail.py @@ -38,6 +38,7 @@ from mail_client.mail_server import get_mail_server_outbound_api from mail_client.utils import ( convert_html_to_text, + get_host_by_ip, get_in_reply_to, get_in_reply_to_mail, parsedate_to_datetime, @@ -368,6 +369,10 @@ def _get_message() -> MIMEMultipart | Message: def _add_headers(message: MIMEMultipart | Message) -> None: """Adds the headers to the message.""" + received_header_value = f"from {get_host_by_ip(self.ip_address)} ({self.ip_address}) by {frappe.local.site} (Frappe Mail Client) via API; {formatdate()}" + received_header = ("Received", received_header_value) + message._headers.insert(0, received_header) + if self.custom_headers: for header in self.custom_headers: message.add_header(header.key, header.value) diff --git a/mail_client/utils/__init__.py b/mail_client/utils/__init__.py index bc8f6fc5..0357779d 100644 --- a/mail_client/utils/__init__.py +++ b/mail_client/utils/__init__.py @@ -1,4 +1,5 @@ import re +import socket from collections.abc import Callable from datetime import datetime from email.utils import parsedate_to_datetime as parsedate @@ -9,7 +10,7 @@ from frappe import _ from frappe.utils import convert_utc_to_system_timezone, get_datetime, get_datetime_str, get_system_timezone from frappe.utils.background_jobs import get_jobs -from frappe.utils.caching import request_cache +from frappe.utils.caching import redis_cache, request_cache @request_cache @@ -108,3 +109,18 @@ def add_or_update_tzinfo(date_time: datetime | str, timezone: str | None = None) date_time = date_time.astimezone(target_tz) return str(date_time) + + +@redis_cache(ttl=3600) +def get_host_by_ip(ip_address: str, raise_exception: bool = False) -> str | None: + """Returns host for the given IP address.""" + + err_msg = None + + try: + return socket.gethostbyaddr(ip_address)[0] + except Exception as e: + err_msg = _(str(e)) + + if raise_exception and err_msg: + frappe.throw(err_msg)