[0] | 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 |
|
---|
[2] | 10 | def __init__(self, mailing_list=None):
|
---|
[0] | 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
|
---|
[2] | 15 | self.reply_to = self.mailing_list.address
|
---|
| 16 | self.raw_email = None
|
---|
[0] | 17 | self.queue = []
|
---|
| 18 | self.archive = self.mailing_list.config.get('archive',
|
---|
[2] | 19 | config.archive_path)
|
---|
[0] | 20 |
|
---|
[2] | 21 | def get_raw_email(self):
|
---|
[0] | 22 | try:
|
---|
[2] | 23 | self.raw_email = sys.stdin.read()
|
---|
[0] | 24 | except:
|
---|
| 25 | raise IOError('Can not get a valid email from stdin')
|
---|
[2] | 26 | return self.raw_email
|
---|
[0] | 27 |
|
---|
[2] | 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
|
---|
[0] | 33 | filename = os.path.join(self.archive,
|
---|
| 34 | datetime.today().strftime('%Y%d%m%H%M%S%f'))
|
---|
| 35 | tmpfile = file(filename, 'w')
|
---|
[2] | 36 | tmpfile.write(self.raw_email)
|
---|
[0] | 37 | tmpfile.close()
|
---|
| 38 | self.queue.append(filename)
|
---|
| 39 |
|
---|
[2] | 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
|
---|
[0] | 48 |
|
---|
[2] | 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()
|
---|
[0] | 54 |
|
---|
[2] | 55 | def run(self):
|
---|
| 56 | self.get_raw_email()
|
---|
| 57 | self.save_raw_email()
|
---|
| 58 | self.send_email()
|
---|