-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.py
87 lines (68 loc) · 1.81 KB
/
source.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import time
import re
import smtplib
import socket
from email.parser import Parser
import database
EMAIL_SERVER_ADDRESS = '127.0.0.1'
EMAIL_SERVER_PORT = 25
def deliver(mailfrom, rcpttos, data):
print 'Sending email from: ', mailfrom, ' to: ', rcpttos
#return
refused = {}
try:
s = smtplib.SMTP(EMAIL_SERVER_ADDRESS, EMAIL_SERVER_PORT, timeout=5)
#s.set_debuglevel(1)
try:
refused = s.sendmail(mailfrom, rcpttos, data)
finally:
s.quit()
except smtplib.SMTPRecipientsRefused, e:
print 'got SMTPRecipientsRefused'
refused = e.recipients
except (socket.error, smtplib.SMTPException), e:
print 'got', e.__class__
# All recipients were refused. If the exception had an associated
# error code, use it. Otherwise,fake it with a non-triggering
# exception code.
errcode = getattr(e, 'smtp_code', -1)
errmsg = getattr(e, 'smtp_error', 'ignore')
for r in rcpttos:
refused[r] = (errcode, errmsg)
return refused
def process_mail(dbcon, mail_id, mail):
#print mail
cur = con.cursor()
cur.execute('select * from forwarding_rules')
rows = cur.fetchall()
for row in rows:
pattern = row[1]
recipient = row[2]
flags = re.S
prog = re.compile(pattern, flags)
result = prog.match(mail)
if result is not None:
mailfrom = Parser().parsestr(mail)['from']
refused = deliver(mailfrom, recipient, mail)
if not refused:
cur.execute('update mails set forwarded = 1 where id = ?', (mail_id,))
dbcon.commit()
return
def poll(dbcon):
while True:
print 'Poll'
# get unprocessed mails
cur = dbcon.cursor()
cur.execute('select * from mails where not forwarded')
rows = cur.fetchall()
for row in rows:
process_mail(dbcon, row[0], row[2])
time.sleep(5)
if __name__ == "__main__":
con = None
try:
con = database.connect_db()
poll(con)
finally:
if con:
con.close()