[0] | 1 | # -*- coding: utf-8 -*-
|
---|
| 2 |
|
---|
[11] | 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 |
|
---|
[0] | 13 | import sys, email, smtplib
|
---|
| 14 | from datetime import datetime
|
---|
| 15 | from models import MailingList
|
---|
| 16 | import config
|
---|
| 17 |
|
---|
| 18 | class Sendmail():
|
---|
| 19 |
|
---|
[10] | 20 | def __init__(self, mailing_list=None, configfile=None):
|
---|
[0] | 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
|
---|
[2] | 25 | self.reply_to = self.mailing_list.address
|
---|
| 26 | self.raw_email = None
|
---|
[0] | 27 | self.queue = []
|
---|
[10] | 28 | self.archive_config = config.get_config_parameters('archive',
|
---|
| 29 | configfile)
|
---|
[0] | 30 |
|
---|
[2] | 31 | def get_raw_email(self):
|
---|
[0] | 32 | try:
|
---|
[2] | 33 | self.raw_email = sys.stdin.read()
|
---|
[0] | 34 | except:
|
---|
| 35 | raise IOError('Can not get a valid email from stdin')
|
---|
[2] | 36 | return self.raw_email
|
---|
[0] | 37 |
|
---|
[2] | 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
|
---|
[10] | 43 | filename = os.path.join(self.archive_config['path'],
|
---|
[0] | 44 | datetime.today().strftime('%Y%d%m%H%M%S%f'))
|
---|
| 45 | tmpfile = file(filename, 'w')
|
---|
[2] | 46 | tmpfile.write(self.raw_email)
|
---|
[0] | 47 | tmpfile.close()
|
---|
| 48 | self.queue.append(filename)
|
---|
| 49 |
|
---|
[2] | 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
|
---|
[0] | 58 |
|
---|
[2] | 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()
|
---|
[0] | 64 |
|
---|
[2] | 65 | def run(self):
|
---|
| 66 | self.get_raw_email()
|
---|
| 67 | self.save_raw_email()
|
---|
| 68 | self.send_email()
|
---|