1 | # -*- coding: utf-8 -*-
|
---|
2 |
|
---|
3 | """
|
---|
4 | The postman project - mta.py
|
---|
5 |
|
---|
6 | This file is released under the BSD license, see LICENSE for
|
---|
7 | more information.
|
---|
8 |
|
---|
9 | Francisco de Borja Lopez Rio - <borja@codigo23.net>
|
---|
10 | Soluciones Informaticas Codigo23 S.L.U. - http://codigo23.net
|
---|
11 | """
|
---|
12 |
|
---|
13 | import sys, email, smtplib
|
---|
14 | from datetime import datetime
|
---|
15 | from models import MailingList
|
---|
16 | import config
|
---|
17 |
|
---|
18 | class Sendmail():
|
---|
19 |
|
---|
20 | def __init__(self, mailing_list=None, configfile=None):
|
---|
21 | if not isinstance(mailing_list, MailingList):
|
---|
22 | raise ValueError(mailing_list, ' is not a valid mailing list')
|
---|
23 | self.mailing_list = mailing_list
|
---|
24 | self.suscriptors = self.mailing_list.members_addresses
|
---|
25 | self.reply_to = self.mailing_list.address
|
---|
26 | self.raw_email = None
|
---|
27 | self.queue = []
|
---|
28 | self.archive_config = config.get_config_parameters('archive',
|
---|
29 | configfile)
|
---|
30 |
|
---|
31 | def get_raw_email(self):
|
---|
32 | try:
|
---|
33 | self.raw_email = sys.stdin.read()
|
---|
34 | except:
|
---|
35 | raise IOError('Can not get a valid email from stdin')
|
---|
36 | return self.raw_email
|
---|
37 |
|
---|
38 | def save_raw_email(self):
|
---|
39 | if not self.raw_email:
|
---|
40 | # FIXME: perhaps a while loop here, with some maximum recursion
|
---|
41 | # check, would be nice here
|
---|
42 | self.get_raw_email
|
---|
43 | filename = os.path.join(self.archive_config['path'],
|
---|
44 | datetime.today().strftime('%Y%d%m%H%M%S%f'))
|
---|
45 | tmpfile = file(filename, 'w')
|
---|
46 | tmpfile.write(self.raw_email)
|
---|
47 | tmpfile.close()
|
---|
48 | self.queue.append(filename)
|
---|
49 |
|
---|
50 | def send_email(self):
|
---|
51 | if self.queue:
|
---|
52 | next_email = self.queue.pop()
|
---|
53 | email_file = file(next_email, 'r')
|
---|
54 | email_data = email.message_from_file(email_file)
|
---|
55 | email_file.close()
|
---|
56 |
|
---|
57 | email_data['Reply-to'] = self.reply_to
|
---|
58 |
|
---|
59 | smtp_conn = smtplib.SMTP()
|
---|
60 | smtp_conn.connect()
|
---|
61 | smtp_conn.sendmail(email_data['From'], self.suscriptors,
|
---|
62 | email_data.as_string())
|
---|
63 | smtp_conn.close()
|
---|
64 |
|
---|
65 | def run(self):
|
---|
66 | self.get_raw_email()
|
---|
67 | self.save_raw_email()
|
---|
68 | self.send_email()
|
---|