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):
|
---|
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_address = self.mailing_list.address
|
---|
16 | self.queue = []
|
---|
17 | self.archive = self.mailing_list.config.get('archive',
|
---|
18 | config.storage_path)
|
---|
19 |
|
---|
20 | def get_raw_email():
|
---|
21 | try:
|
---|
22 | raw_email = sys.stdin.read()
|
---|
23 | except:
|
---|
24 | raise IOError('Can not get a valid email from stdin')
|
---|
25 | return raw_email
|
---|
26 |
|
---|
27 | def save_raw_email():
|
---|
28 | filename = os.path.join(self.archive,
|
---|
29 | datetime.today().strftime('%Y%d%m%H%M%S%f'))
|
---|
30 | tmpfile = file(filename, 'w')
|
---|
31 | tmpfile.write(raw_email)
|
---|
32 | tmpfile.close()
|
---|
33 | self.queue.append(filename)
|
---|
34 |
|
---|
35 | def send_email():
|
---|
36 | if not self.queue:
|
---|
37 | raise ValueError('The emails queue is empty')
|
---|
38 | next_email = self.queue.pop()
|
---|
39 | email_file = file(next_email, 'r')
|
---|
40 | email_data = email.message_from_file(email_file)
|
---|
41 | email_file.close()
|
---|
42 |
|
---|
43 | email_data['Reply-to'] = self.reply_address
|
---|
44 |
|
---|
45 | smtp_conn = smtplib.SMTP()
|
---|
46 | smtp_conn.connect()
|
---|
47 | smtp_conn.sendmail(email_data['From'], self.suscriptors,
|
---|
48 | email_data.as_string())
|
---|
49 | smtp_conn.close()
|
---|