]>
git.immae.eu Git - perso/Immae/Config/Nix.git/blob - systems/eldiron/ejabberd/warn_xmpp_email.py
1 #!@pythonEnv@/bin/python3
10 CONFIG
= json
.load(open("@scriptEnv@", "r"))
14 from unidecode
import unidecode
15 return re
.compile(r
"[^-.A-Za-z0-9_]").sub("_", unidecode(string
))
19 from email
.header
import decode_header
21 mail
= email
.message_from_file(sys
.stdin
)
23 d
= decode_header(mail
["subject"])[0]
25 subject
= d
[0].decode(d
[1])
28 except Exception as e
:
29 subject
= mail
["subject"]
31 recipient
= mail
["X-Original-To"]
36 for part
in mail
.walk():
37 if part
.get_content_type() == "text/plain":
38 body
+= "\n-------------------\n"
40 body
+= part
.get_payload(decode
=True).decode(encoding
=part
.get_content_charset() or "utf-8")
41 except Exception as e
:
42 body
+= part
.get_payload(decode
=False)
43 elif part
.get_content_type() == "text/html":
44 html
= part
.get_payload(decode
=True)
45 elif part
.get_content_type() != "text/html" and\
46 part
.get_content_maintype() != "multipart":
48 filename
= part
.get_filename() or "{}.dat".format(part
["Content-ID"])
49 files
[sanitize(filename
)] = (part
.get_content_type(), part
.get_payload(decode
=True))
51 return [body
, html
, subject
, sender
, recipient
, files
]
53 [body
, html
, subject
, sender
, recipient
, files
] = parse_email()
55 class Bot(slixmpp
.ClientXMPP
):
56 def __init__(self
, jid
, password
, body
, html
, subject
, sender
, recipient
, files
):
57 super().__init
__(jid
, password
)
59 self
.got_error
= False
62 self
.subject
= subject
64 self
.recipient
= recipient
66 self
.register_plugin('xep_0363')
67 self
.add_event_handler("session_start", self
.session_start
)
68 self
.add_event_handler("message", self
.message
)
71 def session_start(self
, event
):
73 if self
.html
is not None:
74 url
= yield from self
['xep_0363'].upload_file(
76 content_type
="text/html",
77 input_file
=io
.BytesIO(self
.html
))
78 files
.append(("HTML version", url
))
80 url
= yield from self
['xep_0363'].upload_file(
82 content_type
=self
.files
[f
][0],
83 input_file
=io
.BytesIO(self
.files
[f
][1])
85 files
.append((f
, url
))
88 New e-mail message from {sender}
91 """.format(sender
=self
.sender
, subject
=self
.subject
, body
=self
.body
)
93 text
+= "\n\nAttachments:"
95 text
+= "\n{}: {}".format(f
[0], f
[1])
96 self
.send_message(mto
=self
.recipient
, mbody
=text
, msubject
=self
.subject
, mtype
='message')
97 yield from asyncio
.sleep(5)
101 def message(self
, msg
):
102 if msg
["type"] == "error":
103 self
.got_error
= True
105 logging
.basicConfig(level
=logging
.DEBUG
, format
='%(levelname)-8s %(message)s')
106 xmpp
= Bot(CONFIG
["jid"], CONFIG
["password"], body
, html
, subject
, sender
, recipient
, files
)
108 xmpp
.process(forever
=False)