1 | # -*- coding: utf-8 -*-
|
---|
2 |
|
---|
3 | import sys, email, smtplib
|
---|
4 | from datetime import datetime
|
---|
5 | from models import MailingList
|
---|
6 | import config
|
---|
7 |
|
---|
8 | class Sendmail():
|
---|
9 |
|
---|
10 | def __init__(self, mailing_list=None):
|
---|
11 | if not isinstance(mailing_list, MailingList):
|
---|
12 | raise ValueError(mailing_list, ' is not a valid mailing list')
|
---|
13 | self.mailing_list = mailing_list
|
---|
14 | self.suscriptors = self.mailing_list.members_addresses
|
---|
15 | self.reply_to = self.mailing_list.address
|
---|
16 | self.raw_email = None
|
---|
17 | self.queue = []
|
---|
18 | self.archive = self.mailing_list.config.get('archive',
|
---|
19 | config.archive_path)
|
---|
20 |
|
---|
21 | def get_raw_email(self):
|
---|
22 | try:
|
---|
23 | self.raw_email = sys.stdin.read()
|
---|
24 | except:
|
---|
25 | raise IOError('Can not get a valid email from stdin')
|
---|
26 | return self.raw_email
|
---|
27 |
|
---|
28 | def save_raw_email(self):
|
---|
29 | if not self.raw_email:
|
---|
30 | # FIXME: perhaps a while loop here, with some maximum recursion
|
---|
31 | # check, would be nice here
|
---|
32 | self.get_raw_email
|
---|
33 | filename = os.path.join(self.archive,
|
---|
34 | datetime.today().strftime('%Y%d%m%H%M%S%f'))
|
---|
35 | tmpfile = file(filename, 'w')
|
---|
36 | tmpfile.write(self.raw_email)
|
---|
37 | tmpfile.close()
|
---|
38 | self.queue.append(filename)
|
---|
39 |
|
---|
40 | def send_email(self):
|
---|
41 | if self.queue:
|
---|
42 | next_email = self.queue.pop()
|
---|
43 | email_file = file(next_email, 'r')
|
---|
44 | email_data = email.message_from_file(email_file)
|
---|
45 | email_file.close()
|
---|
46 |
|
---|
47 | email_data['Reply-to'] = self.reply_to
|
---|
48 |
|
---|
49 | smtp_conn = smtplib.SMTP()
|
---|
50 | smtp_conn.connect()
|
---|
51 | smtp_conn.sendmail(email_data['From'], self.suscriptors,
|
---|
52 | email_data.as_string())
|
---|
53 | smtp_conn.close()
|
---|
54 |
|
---|
55 | def run(self):
|
---|
56 | self.get_raw_email()
|
---|
57 | self.save_raw_email()
|
---|
58 | self.send_email()
|
---|