__init__.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. # This file is related to Radicale - CalDAV and CardDAV server
  2. # for email notifications
  3. # Copyright © 2025-2025 Nate Harris
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. import enum
  18. import re
  19. import smtplib
  20. import ssl
  21. from datetime import datetime, timedelta
  22. from email.encoders import encode_base64
  23. from email.mime.base import MIMEBase
  24. from email.mime.multipart import MIMEMultipart
  25. from email.mime.text import MIMEText
  26. from email.utils import formatdate
  27. from typing import Any, Dict, List, Optional, Sequence, Tuple
  28. import vobject
  29. from radicale.hook import (BaseHook, DeleteHookNotificationItem,
  30. HookNotificationItem, HookNotificationItemTypes)
  31. from radicale.log import logger
  32. PLUGIN_CONFIG_SCHEMA = {
  33. "hook": {
  34. "smtp_server": {
  35. "value": "",
  36. "type": str
  37. },
  38. "smtp_port": {
  39. "value": "",
  40. "type": str
  41. },
  42. "smtp_security": {
  43. "value": "none",
  44. "type": str,
  45. },
  46. "smtp_ssl_verify_mode": {
  47. "value": "REQUIRED",
  48. "type": str,
  49. },
  50. "smtp_username": {
  51. "value": "",
  52. "type": str
  53. },
  54. "smtp_password": {
  55. "value": "",
  56. "type": str
  57. },
  58. "from_email": {
  59. "value": "",
  60. "type": str
  61. },
  62. "added_template": {
  63. "value": """Hello $attendee_name,
  64. You have been added as an attendee to the following calendar event.
  65. $event_title
  66. $event_start_time - $event_end_time
  67. $event_location
  68. This is an automated message. Please do not reply.""",
  69. "type": str
  70. },
  71. "removed_template": {
  72. "value": """Hello $attendee_name,
  73. You have been removed as an attendee from the following calendar event.
  74. $event_title
  75. $event_start_time - $event_end_time
  76. $event_location
  77. This is an automated message. Please do not reply.""",
  78. "type": str
  79. },
  80. "mass_email": {
  81. "value": False,
  82. "type": bool,
  83. }
  84. }
  85. }
  86. MESSAGE_TEMPLATE_VARIABLES = [
  87. "organizer_name",
  88. "from_email",
  89. "attendee_name",
  90. "event_title",
  91. "event_start_time",
  92. "event_end_time",
  93. "event_location",
  94. ]
  95. class SMTP_SECURITY_TYPE_ENUM(enum.Enum):
  96. EMPTY = ""
  97. NONE = "none"
  98. STARTTLS = "starttls"
  99. TLS = "tls"
  100. @classmethod
  101. def from_string(cls, value):
  102. """Convert a string to the corresponding enum value."""
  103. for member in cls:
  104. if member.value == value:
  105. return member
  106. raise ValueError(f"Invalid security type: {value}. Allowed values are: {[m.value for m in cls]}")
  107. class SMTP_SSL_VERIFY_MODE_ENUM(enum.Enum):
  108. EMPTY = ""
  109. NONE = "NONE"
  110. OPTIONAL = "OPTIONAL"
  111. REQUIRED = "REQUIRED"
  112. @classmethod
  113. def from_string(cls, value):
  114. """Convert a string to the corresponding enum value."""
  115. for member in cls:
  116. if member.value == value:
  117. return member
  118. raise ValueError(f"Invalid SSL verify mode: {value}. Allowed values are: {[m.value for m in cls]}")
  119. SMTP_SECURITY_TYPES: Sequence[str] = (SMTP_SECURITY_TYPE_ENUM.NONE.value,
  120. SMTP_SECURITY_TYPE_ENUM.STARTTLS.value,
  121. SMTP_SECURITY_TYPE_ENUM.TLS.value)
  122. SMTP_SSL_VERIFY_MODES: Sequence[str] = (SMTP_SSL_VERIFY_MODE_ENUM.NONE.value,
  123. SMTP_SSL_VERIFY_MODE_ENUM.OPTIONAL.value,
  124. SMTP_SSL_VERIFY_MODE_ENUM.REQUIRED.value)
  125. def ics_contents_contains_invited_event(contents: str):
  126. """
  127. Check if the ICS contents contain an event (versus a VTODO or VJOURNAL).
  128. :param contents: The contents of the ICS file.
  129. :return: True if the ICS file contains an event, False otherwise.
  130. """
  131. cal = vobject.readOne(contents)
  132. return cal.vevent is not None
  133. def extract_email(value: str) -> Optional[str]:
  134. """Extract email address from a string."""
  135. if not value:
  136. return None
  137. value = value.strip().lower()
  138. match = re.search(r"mailto:([^;]+)", value)
  139. if match:
  140. return match.group(1)
  141. # Fallback to the whole value if no mailto found
  142. return value if "@" in value else None
  143. class ContentLine:
  144. _key: str
  145. value: Any
  146. _params: Dict[str, Any]
  147. def __init__(self, key: str, value: Any, params: Optional[Dict[str, Any]] = None):
  148. self._key = key
  149. self.value = value
  150. self._params = params or {}
  151. def _get_param(self, name: str) -> List[Optional[Any]]:
  152. """
  153. Get a parameter value by name.
  154. :param name: The name of the parameter to retrieve.
  155. :return: A list of all matching parameter values, or a single-entry (None) list if the parameter does not exist.
  156. """
  157. return self._params.get(name, [None])
  158. class VComponent:
  159. _vobject_item: vobject.base.Component
  160. def __init__(self,
  161. vobject_item: vobject.base.Component,
  162. component_type: str):
  163. """Initialize a VComponent."""
  164. if not isinstance(vobject_item, vobject.base.Component):
  165. raise ValueError("vobject_item must be a vobject.base.Component")
  166. if vobject_item.name != component_type:
  167. raise ValueError("Invalid component type: %r, expected %r" %
  168. (vobject_item.name, component_type))
  169. self._vobject_item = vobject_item
  170. def _get_content_lines(self, name: str) -> List[ContentLine]:
  171. """Get each matching content line."""
  172. name = name.lower().strip()
  173. _content_lines = self._vobject_item.contents.get(name, None)
  174. if not _content_lines:
  175. return [ContentLine("", None)]
  176. if not isinstance(_content_lines, (list, tuple)):
  177. _content_lines = [_content_lines]
  178. return [ContentLine(key=name, value=cl.value, params=cl.params)
  179. for cl in _content_lines if isinstance(cl, vobject.base.ContentLine)] or [ContentLine("", None)]
  180. def _get_sub_vobjects(self, attribute_name: str, _class: type['VComponent']) -> List[Optional['VComponent']]:
  181. """Get sub vobject items of the specified type if they exist."""
  182. sub_vobjects = getattr(self._vobject_item, attribute_name, None)
  183. if not sub_vobjects:
  184. return [None]
  185. if not isinstance(sub_vobjects, (list, tuple)):
  186. sub_vobjects = [sub_vobjects]
  187. return ([_class(vobject_item=so) for so in sub_vobjects if # type: ignore
  188. isinstance(so, vobject.base.Component)]
  189. or [None])
  190. class Attendee(ContentLine):
  191. def __init__(self, content_line: ContentLine):
  192. super().__init__(key=content_line._key, value=content_line.value,
  193. params=content_line._params)
  194. @property
  195. def email(self) -> Optional[str]:
  196. """Return the email address of the attendee."""
  197. return extract_email(self.value)
  198. @property
  199. def role(self) -> Optional[str]:
  200. """Return the role of the attendee."""
  201. return self._get_param("ROLE")[0]
  202. @property
  203. def participation_status(self) -> Optional[str]:
  204. """Return the participation status of the attendee."""
  205. return self._get_param("PARTSTAT")[0]
  206. @property
  207. def name(self) -> Optional[str]:
  208. return self._get_param("CN")[0]
  209. @property
  210. def delegated_from(self) -> Optional[str]:
  211. """Return the email address of the attendee who delegated this attendee."""
  212. delegate = self._get_param("DELEGATED-FROM")[0]
  213. return extract_email(delegate) if delegate else None
  214. class TimeWithTimezone(ContentLine):
  215. def __init__(self, content_line: ContentLine):
  216. """Initialize a time with timezone content line."""
  217. super().__init__(key=content_line._key, value=content_line.value,
  218. params=content_line._params)
  219. @property
  220. def timezone_id(self) -> Optional[str]:
  221. """Return the timezone of the time."""
  222. return self._get_param("TZID")[0]
  223. @property
  224. def time(self) -> Optional[datetime]:
  225. """Return the time value."""
  226. return self.value
  227. def time_string(self, _format: str = "%Y-%m-%d %H:%M:%S") -> Optional[str]:
  228. """Return the time as a formatted string."""
  229. if self.time:
  230. return self.time.strftime(_format)
  231. return None
  232. class Alarm(VComponent):
  233. def __init__(self,
  234. vobject_item: vobject.base.Component):
  235. """Initialize a VALARM item."""
  236. super().__init__(vobject_item, "VALARM")
  237. @property
  238. def action(self) -> Optional[str]:
  239. """Return the action of the alarm."""
  240. return self._get_content_lines("ACTION")[0].value
  241. @property
  242. def description(self) -> Optional[str]:
  243. """Return the description of the alarm."""
  244. return self._get_content_lines("DESCRIPTION")[0].value
  245. @property
  246. def trigger(self) -> Optional[timedelta]:
  247. """Return the trigger of the alarm."""
  248. return self._get_content_lines("TRIGGER")[0].value
  249. @property
  250. def repeat(self) -> Optional[int]:
  251. """Return the repeat interval of the alarm."""
  252. repeat = self._get_content_lines("REPEAT")[0].value
  253. return int(repeat) if repeat is not None else None
  254. @property
  255. def duration(self) -> Optional[str]:
  256. """Return the duration of the alarm."""
  257. return self._get_content_lines("DURATION")[0].value
  258. class SubTimezone(VComponent):
  259. def __init__(self,
  260. vobject_item: vobject.base.Component,
  261. component_type: str):
  262. """Initialize a sub VTIMEZONE item."""
  263. super().__init__(vobject_item, component_type)
  264. @property
  265. def datetime_start(self) -> Optional[datetime]:
  266. """Return the start datetime of the timezone."""
  267. return self._get_content_lines("DTSTART")[0].value
  268. @property
  269. def timezone_name(self) -> Optional[str]:
  270. """Return the timezone name."""
  271. return self._get_content_lines("TZNAME")[0].value
  272. @property
  273. def timezone_offset_from(self) -> Optional[str]:
  274. """Return the timezone offset from."""
  275. return self._get_content_lines("TZOFFSETFROM")[0].value
  276. @property
  277. def timezone_offset_to(self) -> Optional[str]:
  278. """Return the timezone offset to."""
  279. return self._get_content_lines("TZOFFSETTO")[0].value
  280. class StandardTimezone(SubTimezone):
  281. def __init__(self,
  282. vobject_item: vobject.base.Component):
  283. """Initialize a STANDARD item."""
  284. super().__init__(vobject_item, "STANDARD")
  285. class DaylightTimezone(SubTimezone):
  286. def __init__(self,
  287. vobject_item: vobject.base.Component):
  288. """Initialize a DAYLIGHT item."""
  289. super().__init__(vobject_item, "DAYLIGHT")
  290. class Timezone(VComponent):
  291. def __init__(self,
  292. vobject_item: vobject.base.Component):
  293. """Initialize a VTIMEZONE item."""
  294. super().__init__(vobject_item, "VTIMEZONE")
  295. @property
  296. def timezone_id(self) -> Optional[str]:
  297. """Return the timezone ID."""
  298. return self._get_content_lines("TZID")[0].value
  299. @property
  300. def standard(self) -> Optional[StandardTimezone]:
  301. """Return the STANDARD subcomponent if it exists."""
  302. return self._get_sub_vobjects("standard", StandardTimezone)[0] # type: ignore
  303. @property
  304. def daylight(self) -> Optional[DaylightTimezone]:
  305. """Return the DAYLIGHT subcomponent if it exists."""
  306. return self._get_sub_vobjects("daylight", DaylightTimezone)[0] # type: ignore
  307. class Event(VComponent):
  308. def __init__(self,
  309. vobject_item: vobject.base.Component):
  310. """Initialize a VEVENT item."""
  311. super().__init__(vobject_item, "VEVENT")
  312. @property
  313. def datetime_stamp(self) -> Optional[str]:
  314. """Return the last modification datetime of the event."""
  315. return self._get_content_lines("DTSTAMP")[0].value
  316. @property
  317. def datetime_start(self) -> Optional[TimeWithTimezone]:
  318. """Return the start datetime of the event."""
  319. _content_line = self._get_content_lines("DTSTART")[0]
  320. return TimeWithTimezone(_content_line) if _content_line.value else None
  321. @property
  322. def datetime_end(self) -> Optional[TimeWithTimezone]:
  323. """Return the end datetime of the event. Either this or duration will be available, but not both."""
  324. _content_line = self._get_content_lines("DTEND")[0]
  325. return TimeWithTimezone(_content_line) if _content_line.value else None
  326. @property
  327. def duration(self) -> Optional[int]:
  328. """Return the duration of the event. Either this or datetime_end will be available, but not both."""
  329. return self._get_content_lines("DURATION")[0].value
  330. @property
  331. def uid(self) -> Optional[str]:
  332. """Return the UID of the event."""
  333. return self._get_content_lines("UID")[0].value
  334. @property
  335. def status(self) -> Optional[str]:
  336. """Return the status of the event."""
  337. return self._get_content_lines("STATUS")[0].value
  338. @property
  339. def summary(self) -> Optional[str]:
  340. """Return the summary of the event."""
  341. return self._get_content_lines("SUMMARY")[0].value
  342. @property
  343. def location(self) -> Optional[str]:
  344. """Return the location of the event."""
  345. return self._get_content_lines("LOCATION")[0].value
  346. @property
  347. def organizer(self) -> Optional[str]:
  348. """Return the organizer of the event."""
  349. return self._get_content_lines("ORGANIZER")[0].value
  350. @property
  351. def alarms(self) -> List[Alarm]:
  352. """Return a list of VALARM items in the event."""
  353. return self._get_sub_vobjects("valarm", Alarm) # type: ignore # Can be multiple
  354. @property
  355. def attendees(self) -> List[Attendee]:
  356. """Return a list of ATTENDEE items in the event."""
  357. _content_lines = self._get_content_lines("ATTENDEE")
  358. return [Attendee(content_line=attendee) for attendee in _content_lines if attendee.value is not None]
  359. class Calendar(VComponent):
  360. def __init__(self,
  361. vobject_item: vobject.base.Component):
  362. """Initialize a VCALENDAR item."""
  363. super().__init__(vobject_item, "VCALENDAR")
  364. @property
  365. def version(self) -> Optional[str]:
  366. """Return the version of the calendar."""
  367. return self._get_content_lines("VERSION")[0].value
  368. @property
  369. def product_id(self) -> Optional[str]:
  370. """Return the product ID of the calendar."""
  371. return self._get_content_lines("PRODID")[0].value
  372. @property
  373. def event(self) -> Optional[Event]:
  374. """Return the VEVENT item in the calendar."""
  375. return self._get_sub_vobjects("vevent", Event)[0] # type: ignore
  376. # TODO: Add VTODO and VJOURNAL support if needed
  377. @property
  378. def timezone(self) -> Optional[Timezone]:
  379. """Return the VTIMEZONE item in the calendar."""
  380. return self._get_sub_vobjects("vtimezone", Timezone)[0] # type: ignore
  381. class EmailEvent:
  382. def __init__(self,
  383. event: Event,
  384. ics_content: str,
  385. ics_file_name: str):
  386. self.event = event
  387. self.ics_content = ics_content
  388. self.file_name = ics_file_name
  389. class ICSEmailAttachment:
  390. def __init__(self, file_content: str, file_name: str):
  391. self.file_content = file_content
  392. self.file_name = file_name
  393. def prepare_email_part(self) -> MIMEBase:
  394. # Add file as application/octet-stream
  395. # Email client can usually download this automatically as attachment
  396. part = MIMEBase("application", "octet-stream")
  397. part.set_payload(self.file_content)
  398. # Encode file in ASCII characters to send by email
  399. encode_base64(part)
  400. # Add header as key/value pair to attachment part
  401. part.add_header(
  402. "Content-Disposition",
  403. f"attachment; filename= {self.file_name}",
  404. )
  405. return part
  406. class MessageTemplate:
  407. def __init__(self, subject: str, body: str):
  408. self.subject = subject
  409. self.body = body
  410. if not self._validate_template(template=subject):
  411. raise ValueError(
  412. f"Invalid subject template: {subject}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  413. if not self._validate_template(template=body):
  414. raise ValueError(f"Invalid body template: {body}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  415. def __repr__(self):
  416. return f'MessageTemplate(subject={self.subject}, body={self.body})'
  417. def __str__(self):
  418. return f'{self.subject}: {self.body}'
  419. def _validate_template(self, template: str) -> bool:
  420. """
  421. Validate the template to ensure it contains only allowed variables.
  422. :param template: The template string to validate.
  423. :return: True if the template is valid, False otherwise.
  424. """
  425. # Find all variables in the template (starting with $)
  426. variables = re.findall(r'\$(\w+)', template)
  427. # Check if all variables are in the allowed list
  428. for var in variables:
  429. if var not in MESSAGE_TEMPLATE_VARIABLES:
  430. logger.error(
  431. f"Invalid variable '{var}' found in template. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  432. return False
  433. return True
  434. def _populate_template(self, template: str, context: dict) -> str:
  435. """
  436. Populate the template with the provided context.
  437. :param template: The template string to populate.
  438. :param context: A dictionary containing the context variables.
  439. :return: The populated template string.
  440. """
  441. for key, value in context.items():
  442. template = template.replace(f"${key}", str(value or ""))
  443. return template
  444. def build_message(self, event: EmailEvent, from_email: str, mass_email: bool,
  445. attendee: Optional[Attendee] = None) -> str:
  446. """
  447. Build the message body using the template.
  448. :param event: The event to include in the message.
  449. :param from_email: The email address of the sender.
  450. :param mass_email: Whether this is a mass email to multiple attendees.
  451. :param attendee: The specific attendee to include in the message, if not a mass email.
  452. :return: The formatted message body.
  453. """
  454. if mass_email:
  455. # If this is a mass email, we do not use individual attendee names
  456. attendee_name = "everyone"
  457. else:
  458. assert attendee is not None, "Attendee must be provided for non-mass emails"
  459. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  460. context = {
  461. "attendee_name": attendee_name,
  462. "from_email": from_email,
  463. "organizer_name": event.event.organizer or "Unknown Organizer",
  464. "event_title": event.event.summary or "No Title",
  465. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  466. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  467. "event_location": event.event.location or "No Location Specified",
  468. }
  469. return self._populate_template(template=self.body, context=context)
  470. def build_subject(self, event: EmailEvent, from_email: str, mass_email: bool,
  471. attendee: Optional[Attendee] = None) -> str:
  472. """
  473. Build the message subject using the template.
  474. :param attendee: The attendee to include in the subject.
  475. :param event: The event to include in the subject.
  476. :param from_email: The email address of the sender.
  477. :param mass_email: Whether this is a mass email to multiple attendees.
  478. :param attendee: The specific attendee to include in the message, if not a mass email.
  479. :return: The formatted message subject.
  480. """
  481. if mass_email:
  482. # If this is a mass email, we do not use individual attendee names
  483. attendee_name = "everyone"
  484. else:
  485. assert attendee is not None, "Attendee must be provided for non-mass emails"
  486. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  487. context = {
  488. "attendee_name": attendee_name,
  489. "from_email": from_email,
  490. "organizer_name": event.event.organizer or "Unknown Organizer",
  491. "event_title": event.event.summary or "No Title",
  492. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  493. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  494. "event_location": event.event.location or "No Location Specified",
  495. }
  496. return self._populate_template(template=self.subject, context=context)
  497. class EmailConfig:
  498. def __init__(self,
  499. host: str,
  500. port: int,
  501. security: str,
  502. ssl_verify_mode: str,
  503. username: str,
  504. password: str,
  505. from_email: str,
  506. send_mass_emails: bool,
  507. dryrun: bool,
  508. added_template: MessageTemplate,
  509. removed_template: MessageTemplate):
  510. self.host = host
  511. self.port = port
  512. self.security = SMTP_SECURITY_TYPE_ENUM.from_string(value=security)
  513. self.ssl_verify_mode = SMTP_SSL_VERIFY_MODE_ENUM.from_string(value=ssl_verify_mode)
  514. self.username = username
  515. self.password = password
  516. self.from_email = from_email
  517. self.send_mass_emails = send_mass_emails
  518. self.dryrun = dryrun
  519. self.added_template = added_template
  520. self.removed_template = removed_template
  521. self.updated_template = added_template # Reuse added template for updated events
  522. self.deleted_template = removed_template # Reuse removed template for deleted events
  523. def __str__(self) -> str:
  524. """
  525. Return a string representation of the EmailConfig.
  526. """
  527. return f"EmailConfig(host={self.host}, port={self.port}, username={self.username}, " \
  528. f"from_email={self.from_email}, send_mass_emails={self.send_mass_emails}, dryrun={self.dryrun})"
  529. def __repr__(self):
  530. return self.__str__()
  531. def send_added_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  532. """
  533. Send a notification for added attendees.
  534. :param attendees: The attendees to inform.
  535. :param event: The event the attendee is being added to.
  536. :return: True if the email was sent successfully, False otherwise.
  537. """
  538. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  539. return self._prepare_and_send_email(template=self.added_template, attendees=attendees, event=event,
  540. ics_attachment=ics_attachment)
  541. def send_removed_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  542. """
  543. Send a notification for removed attendees.
  544. :param attendees: The attendees to inform.
  545. :param event: The event the attendee is being removed from.
  546. :return: True if the email was sent successfully, False otherwise.
  547. """
  548. return self._prepare_and_send_email(template=self.removed_template, attendees=attendees, event=event,
  549. ics_attachment=None)
  550. def send_updated_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  551. """
  552. Send a notification for updated events.
  553. :param attendees: The attendees to inform.
  554. :param event: The event being updated.
  555. :return: True if the email was sent successfully, False otherwise.
  556. """
  557. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  558. return self._prepare_and_send_email(template=self.updated_template, attendees=attendees, event=event,
  559. ics_attachment=ics_attachment)
  560. def send_deleted_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  561. """
  562. Send a notification for deleted events.
  563. :param attendees: The attendees to inform.
  564. :param event: The event being deleted.
  565. :return: True if the email was sent successfully, False otherwise.
  566. """
  567. return self._prepare_and_send_email(template=self.deleted_template, attendees=attendees, event=event,
  568. ics_attachment=None)
  569. def _prepare_and_send_email(self, template: MessageTemplate, attendees: List[Attendee],
  570. event: EmailEvent, ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  571. """
  572. Prepare the email message(s) and send them to the attendees.
  573. :param template: The message template to use for the email.
  574. :param attendees: The list of attendees to notify.
  575. :param event: The event to include in the email.
  576. :param ics_attachment: An optional ICS attachment to include in the email.
  577. :return: True if the email(s) were sent successfully, False otherwise.
  578. """
  579. if self.send_mass_emails:
  580. # If mass emails are enabled, we send one email to all attendees
  581. body = template.build_message(event=event, from_email=self.from_email,
  582. mass_email=self.send_mass_emails, attendee=None)
  583. subject = template.build_subject(event=event, from_email=self.from_email,
  584. mass_email=self.send_mass_emails, attendee=None)
  585. return self._send_email(subject=subject, body=body, attendees=attendees, ics_attachment=ics_attachment)
  586. else:
  587. failure_encountered = False
  588. for attendee in attendees:
  589. # For individual emails, we send one email per attendee
  590. body = template.build_message(event=event, from_email=self.from_email,
  591. mass_email=self.send_mass_emails, attendee=attendee)
  592. subject = template.build_subject(event=event, from_email=self.from_email,
  593. mass_email=self.send_mass_emails, attendee=attendee)
  594. if not self._send_email(subject=subject, body=body, attendees=[attendee],
  595. ics_attachment=ics_attachment):
  596. failure_encountered = True
  597. return not failure_encountered # Return True if all emails were sent successfully
  598. def _build_context(self) -> ssl.SSLContext:
  599. """
  600. Build the SSL context based on the configured security and SSL verify mode.
  601. :return: An SSLContext object configured for the SMTP connection.
  602. """
  603. context = ssl.create_default_context()
  604. if self.ssl_verify_mode == SMTP_SSL_VERIFY_MODE_ENUM.REQUIRED:
  605. context.check_hostname = True
  606. context.verify_mode = ssl.CERT_REQUIRED
  607. elif self.ssl_verify_mode == SMTP_SSL_VERIFY_MODE_ENUM.OPTIONAL:
  608. context.check_hostname = True
  609. context.verify_mode = ssl.CERT_OPTIONAL
  610. else:
  611. context.check_hostname = False
  612. context.verify_mode = ssl.CERT_NONE
  613. return context
  614. def _send_email(self,
  615. subject: str,
  616. body: str,
  617. attendees: List[Attendee],
  618. ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  619. """
  620. Send the notification using the email service.
  621. :param subject: The subject of the notification.
  622. :param body: The body of the notification.
  623. :param attendees: The attendees to notify.
  624. :param ics_attachment: An optional ICS attachment to include in the email.
  625. :return: True if the email was sent successfully, False otherwise.
  626. """
  627. to_addresses = [attendee.email for attendee in attendees if attendee.email]
  628. if not to_addresses:
  629. logger.warning("No valid email addresses found in attendees. Cannot send email.")
  630. return False
  631. if self.dryrun is True:
  632. logger.warning("Hook 'email': DRY-RUN _send_email / to_addresses=%r", to_addresses)
  633. return True
  634. # Add headers
  635. message = MIMEMultipart("mixed")
  636. message["From"] = self.from_email
  637. message["Reply-To"] = self.from_email
  638. message["Subject"] = subject
  639. message["Date"] = formatdate(localtime=True)
  640. # Add body text
  641. message.attach(MIMEText(body, "plain"))
  642. # Add ICS attachment if provided
  643. if ics_attachment:
  644. ical_attachment = ics_attachment.prepare_email_part()
  645. message.attach(ical_attachment)
  646. # Convert message to text
  647. text = message.as_string()
  648. try:
  649. if self.security == SMTP_SECURITY_TYPE_ENUM.EMPTY:
  650. logger.warning("SMTP security type is empty, raising ValueError.")
  651. raise ValueError("SMTP security type cannot be empty. Please specify a valid security type.")
  652. elif self.security == SMTP_SECURITY_TYPE_ENUM.NONE:
  653. server = smtplib.SMTP(host=self.host, port=self.port)
  654. elif self.security == SMTP_SECURITY_TYPE_ENUM.STARTTLS:
  655. context = self._build_context()
  656. server = smtplib.SMTP(host=self.host, port=self.port)
  657. server.ehlo() # Identify self to server
  658. server.starttls(context=context) # Start TLS connection
  659. server.ehlo() # Identify again after starting TLS
  660. elif self.security == SMTP_SECURITY_TYPE_ENUM.TLS:
  661. context = self._build_context()
  662. server = smtplib.SMTP_SSL(host=self.host, port=self.port, context=context)
  663. if self.username and self.password:
  664. logger.debug("Logging in to SMTP server with username: %s", self.username)
  665. server.login(user=self.username, password=self.password)
  666. errors: Dict[str, Tuple[int, bytes]] = server.sendmail(from_addr=self.from_email, to_addrs=to_addresses,
  667. msg=text)
  668. logger.debug("Email sent successfully to %s", to_addresses)
  669. server.quit()
  670. except smtplib.SMTPException as e:
  671. logger.error(f"SMTP error occurred: {e}")
  672. return False
  673. if errors:
  674. for email, (code, error) in errors.items():
  675. logger.error(f"Failed to send email to {email}: {str(error)} (Code: {code})")
  676. return False
  677. return True
  678. def _read_event(vobject_data: str) -> EmailEvent:
  679. """
  680. Read the vobject item from the provided string and create an EmailEvent.
  681. """
  682. v_cal: vobject.base.Component = vobject.readOne(vobject_data)
  683. cal: Calendar = Calendar(vobject_item=v_cal)
  684. event: Event = cal.event # type: ignore
  685. return EmailEvent(
  686. event=event,
  687. ics_content=vobject_data,
  688. ics_file_name="event.ics"
  689. )
  690. class Hook(BaseHook):
  691. def __init__(self, configuration):
  692. super().__init__(configuration)
  693. self.dryrun = self.configuration.get("hook", "dryrun")
  694. self.email_config = EmailConfig(
  695. host=self.configuration.get("hook", "smtp_server"),
  696. port=self.configuration.get("hook", "smtp_port"),
  697. security=self.configuration.get("hook", "smtp_security"),
  698. ssl_verify_mode=self.configuration.get("hook", "smtp_ssl_verify_mode"),
  699. username=self.configuration.get("hook", "smtp_username"),
  700. password=self.configuration.get("hook", "smtp_password"),
  701. from_email=self.configuration.get("hook", "from_email"),
  702. send_mass_emails=self.configuration.get("hook", "mass_email"),
  703. dryrun=self.configuration.get("hook", "dryrun"),
  704. added_template=MessageTemplate(
  705. subject="You have been added to an event",
  706. body=self.configuration.get("hook", "added_template")
  707. ),
  708. removed_template=MessageTemplate(
  709. subject="You have been removed from an event",
  710. body=self.configuration.get("hook", "removed_template")
  711. ),
  712. )
  713. logger.info(
  714. "Email hook initialized with configuration: %s",
  715. self.email_config
  716. )
  717. def notify(self, notification_item) -> None:
  718. """
  719. Entrypoint for processing a single notification item.
  720. Overrides default notify method from BaseHook.
  721. Triggered by Radicale when a notifiable event occurs (e.g. item added, updated or deleted)
  722. """
  723. if isinstance(notification_item, HookNotificationItem):
  724. self._process_event_and_notify(notification_item)
  725. def _process_event_and_notify(self, notification_item: HookNotificationItem) -> None:
  726. """
  727. Process the event and send an email notification.
  728. :param notification_item: The single item to process.
  729. :type notification_item: HookNotificationItem
  730. :return: None
  731. """
  732. if self.dryrun:
  733. logger.warning("Hook 'email': DRY-RUN received notification_item: %r", vars(notification_item))
  734. else:
  735. logger.debug("Received notification_item: %r", vars(notification_item))
  736. try:
  737. notification_type = HookNotificationItemTypes(value=notification_item.type)
  738. except ValueError:
  739. logger.warning("Unknown notification item type: %s", notification_item.type)
  740. return
  741. if notification_type == HookNotificationItemTypes.CPATCH:
  742. # Ignore cpatch notifications (PROPPATCH requests for WebDAV metadata updates)
  743. return
  744. elif notification_type == HookNotificationItemTypes.UPSERT:
  745. # Handle upsert notifications (POST request for new item and PUT for updating existing item)
  746. # We don't have access to the original content for a PUT request, just the incoming data
  747. item_str: str = notification_item.content # type: ignore # A serialized vobject.base.Component
  748. if not ics_contents_contains_invited_event(contents=item_str):
  749. # If the ICS file does not contain an event, we do not send any notifications.
  750. logger.debug("No event found in the ICS file, skipping notification.")
  751. return
  752. email_event: EmailEvent = _read_event(vobject_data=item_str) # type: ignore
  753. email_success: bool = self.email_config.send_updated_email( # type: ignore
  754. attendees=email_event.event.attendees,
  755. event=email_event
  756. )
  757. if not email_success:
  758. logger.error("Failed to send some or all email notifications for event: %s", email_event.event.uid)
  759. return
  760. elif notification_type == HookNotificationItemTypes.DELETE:
  761. # Handle delete notifications (DELETE requests)
  762. # Ensure it's a delete notification, as we need the old content
  763. if not isinstance(notification_item, DeleteHookNotificationItem):
  764. return
  765. item_str: str = notification_item.old_content # type: ignore # A serialized vobject.base.Component
  766. if not ics_contents_contains_invited_event(contents=item_str):
  767. # If the ICS file does not contain an event, we do not send any notifications.
  768. logger.debug("No event found in the ICS file, skipping notification.")
  769. return
  770. email_event: EmailEvent = _read_event(vobject_data=item_str) # type: ignore
  771. email_success: bool = self.email_config.send_deleted_email( # type: ignore
  772. attendees=email_event.event.attendees,
  773. event=email_event
  774. )
  775. if not email_success:
  776. logger.error("Failed to send some or all email notifications for event: %s", email_event.event.uid)
  777. return
  778. return