#!/usr/bin/python #-*- mode: python; coding: koi8-r -*- import sys, os from StringIO import StringIO import os import MySQLdb from string import split, lstrip, rstrip from email import * import smtplib def emailing(list_id, text, filename=None, attach=None, filetype=None): msg = MIMEMultipart.MIMEMultipart() db = MySQLdb.connect(host='', db='', user='', passwd='') msg['Subject'] = Header.Header("Тема письма","koi8-r").encode() msg['From'] = Utils.formataddr((Header.Header("Ваша любящая компания","koi8-r").encode(), 'postmaster@yourdomain.com')) message = StringIO() message.write(text) txt = MIMEText.MIMEText(message.getvalue(),'plain','koi8-r') message.close() msg.attach(txt) if filename: doc = MIMEBase.MIMEBase('application',filetype) doc.set_payload(attach) Encoders.encode_base64(doc) doc.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(doc) # cycle through the emails of subscribers cur.execute("select email from youremaildtable") for line in cur.fetchall(): try: msg.replace_header('To',Utils.formataddr(('',line[0]))) except KeyError: msg['To'] = Utils.formataddr(('',line[0])) s = smtplib.SMTP() s.connect() try: s.sendmail('postmaster@yourdomain.com', line[0], msg.as_string()) except smtplib.SMTPRecipientsRefused, msg: s.sendmail('postmaster@yourdomain.com', 'postmaster@yourdomain.com', "To: \nSubject: Maillist send error\n\n%s"%(msg)) s.close() cur.close() db.close() def main(): buf = StringIO() map(buf.write,sys.stdin) msg = message_from_string(buf.getvalue()) buf.close() print rstrip(lstrip(split(msg.get('Return-Path'))[-1],'<'),'>') if rstrip(lstrip(split(msg.get('Return-Path'))[-1],'<'),'>') == 'postmaster@yourdomain.com': subj = Header.decode_header(msg.get('Subject'))[0][0] for part in msg.walk(): if part.get_content_type() == 'text/plain': text = part.get_payload(decode=1) filetype = 'text' if part.get_content_type() == 'application/msword': filename = Header.decode_header(part.get_filename())[0][0] attach = part.get_payload(decode=1) filetype = 'word' if part.get_content_type() == 'application/pdf': filename = Header.decode_header(part.get_filename())[0][0] attach = part.get_payload(decode=1) filetype = 'pdf' else: filename = None attach = None filetype = None emailing(subj,text,filename,attach,filetype) if __name__ == '__main__': main()