1
0
mirror of https://github.com/Mailu/Mailu.git synced 2024-12-14 10:53:30 +02:00
Mailu/fetchmail/fetchmail.py

87 lines
2.5 KiB
Python
Raw Normal View History

2016-04-28 20:07:38 +02:00
#!/usr/bin/env python
import sqlite3
import time
import os
import tempfile
2016-09-10 12:27:43 +02:00
import shlex
import subprocess
2016-04-28 20:07:38 +02:00
2016-06-26 13:54:16 +02:00
FETCHMAIL = """
fetchmail -N \
--sslcertck --sslcertpath /etc/ssl/certs \
-f {}
"""
2016-04-28 20:07:38 +02:00
RC_LINE = """
poll "{host}" proto {protocol} port {port}
2016-04-28 20:07:38 +02:00
user "{username}" password "{password}"
is "{user_email}"
2016-04-28 20:07:38 +02:00
smtphost "smtp"
{options}
sslproto 'AUTO'
2016-04-28 20:07:38 +02:00
"""
2016-09-10 12:27:43 +02:00
def escape_rc_string(arg):
return arg.replace("\\", "\\\\").replace('"', '\\"')
2016-04-28 20:07:38 +02:00
def fetchmail(fetchmailrc):
with tempfile.NamedTemporaryFile() as handler:
handler.write(fetchmailrc.encode("utf8"))
handler.flush()
command = FETCHMAIL.format(shlex.quote(handler.name))
output = subprocess.check_output(command, shell=True)
return output
2016-04-28 20:07:38 +02:00
def run(connection, cursor):
2016-04-28 20:07:38 +02:00
cursor.execute("""
SELECT user_email, protocol, host, port, tls, username, password
2016-04-28 20:07:38 +02:00
FROM fetch
""")
for line in cursor.fetchall():
fetchmailrc = ""
user_email, protocol, host, port, tls, username, password = line
options = "options fetchall antispam 501, 504, 550, 553, 554"
options += " ssl" if tls else ""
2016-04-28 20:07:38 +02:00
fetchmailrc += RC_LINE.format(
2016-09-10 12:27:43 +02:00
user_email=escape_rc_string(user_email),
2016-04-28 20:07:38 +02:00
protocol=protocol,
2016-09-10 12:27:43 +02:00
host=escape_rc_string(host),
2016-04-28 20:07:38 +02:00
port=port,
2016-09-10 12:27:43 +02:00
username=escape_rc_string(username),
password=escape_rc_string(password),
2016-04-28 20:07:38 +02:00
options=options
)
try:
print(fetchmail(fetchmailrc))
error_message = ""
except subprocess.CalledProcessError as error:
error_message = error.output.decode("utf8")
# No mail is not an error
if not (error_message.startswith("fetchmail: No mail")):
# activate the next statement to log the poll command
# Warning: the poll command contains the mailbox password
# in clear text
#print(fetchmailrc)
print(fetchmailrc)
finally:
cursor.execute("""
UPDATE fetch SET error=?, last_check=datetime('now')
WHERE user_email=?
""", (error_message.split("\n")[0], user_email))
connection.commit()
2016-04-28 20:07:38 +02:00
if __name__ == "__main__":
db_path = os.environ.get("DB_PATH", "/data/freeposte.db")
connection = sqlite3.connect(db_path)
while True:
cursor = connection.cursor()
run(connection, cursor)
2016-04-28 20:07:38 +02:00
cursor.close()
time.sleep(int(os.environ.get("FETCHMAIL_DELAY", 60)))