extras-repoclosure Mailer.py,NONE,1.1 rc-report.py,1.62,1.63

Michael Schwendt mschwendt at fedoraproject.org
Tue Aug 4 09:34:15 UTC 2009


Author: mschwendt

Update of /cvs/fedora/extras-repoclosure
In directory cvs1.fedora.phx.redhat.com:/tmp/cvs-serv1429

Modified Files:
	rc-report.py 
Added Files:
	Mailer.py 
Log Message:
split off the smtplib usage into an external module that is smarter and tries to reconnect after unexpected server disconnects [with remote smtp servers]


--- NEW FILE Mailer.py ---
#!/usr/bin/python -t
# -*- coding: utf-8 -*-
# -*- mode: Python; indent-tabs-mode: nil; -*-

import smtplib
import time
import email.Charset
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
from email.Utils import make_msgid

class Mailer(smtplib.SMTP):

    def __init__(self, host='localhost', user=None, passwd=None, tls=False):
        self._host = host
        if user and len(user)>0:
            self._user = user
        else:
            self._user = user
        if passwd and len(passwd)>0:
            self._passwd = passwd
        else:
            self._passwd = passwd
        self._tls = tls
        self._ready = False

        self.maxmailsize = 0
        self.retries = 3
        self.waitsecs = 2

    def tryconnect(self):
        if self._host:
            smtplib.SMTP.__init__(self, self._host)
        else:
            smtplib.SMTP.__init__(self)
        #self.set_debuglevel(1)
        if ( self._tls ):
            self.ehlo()
            self.starttls()
            self.ehlo()
        if ( self._user and self._passwd ):
            self.login(self._user, self._passwd)
        self._ready = True

    def _printerror(self,tuple):
        (num,error) = tuple
        print error, '(%s)'%num

    def quit(self):
        if self._ready:
            smtplib.SMTP.quit(self)
    
    def sendmail( self, fromaddr, to, replyto, subject, body):
        if isinstance(to, basestring):
            to = [to]

        if self.maxmailsize:
            return self._mailsplit(fromaddr, to, replyto, subject, body)
        else:
            return self._mail(fromaddr, to, replyto, subject, body)

    def _mail(self, fromaddr, tolist, replytoaddr, subject, body):
        email.Charset.add_charset('utf-8', email.Charset.SHORTEST, None, None)
        msg = MIMEText(body, 'plain', 'utf-8')
        msg['Subject'] = Header(subject)
        msg['From'] = Header(fromaddr)
        if replytoaddr:
            msg['ReplyTo'] = Header(replytoaddr)
        msg['To'] = Header(','.join(tolist))
        msg['Date'] = formatdate()
        msg['Message-Id'] = make_msgid()

        for i in range(self.retries):
            try:
                if not self._ready:
                    self.tryconnect()
                rv = smtplib.SMTP.sendmail(self, fromaddr, tolist, msg.as_string(False))
                return rv
            except smtplib.SMTPServerDisconnected, e:
                print e
                self._ready = False
                time.sleep(self.waitsecs)

    def _mailsplit(self, fromaddr, toaddrs, replytoaddr, subject, body):
        # Split mail body at line positions to keep it below maxmailsize.
        parts = 0
        start = 0
        end = len(body)
        slices = []
        while ( start < end ):
            if ( (end-start) > self.maxmailsize ):
                nextstart = body.rfind( '\n', start, start+self.maxmailsize )
                if ( nextstart<0 or nextstart==start ):
                    print 'ERROR: cannot split mail body cleanly'
                    nextstart = end
            else:
                nextstart = end
            slices.append( (start, nextstart) )
            start = nextstart
            parts += 1

        curpart = 1
        for (start,end) in slices:
            if (parts>1):
                subjectmodified = ( '(%d/%d) %s' % (curpart, parts, subject) )
                time.sleep(1)
            else:
                subjectmodified = subject
            slicedbody = body[start:end]
            self._mail(fromaddr,toaddrs,replytoaddr,subjectmodified,slicedbody)
            curpart += 1



Index: rc-report.py
===================================================================
RCS file: /cvs/fedora/extras-repoclosure/rc-report.py,v
retrieving revision 1.62
retrieving revision 1.63
diff -u -r1.62 -r1.63
--- rc-report.py	9 Jun 2009 12:16:43 -0000	1.62
+++ rc-report.py	4 Aug 2009 09:34:15 -0000	1.63
@@ -3,11 +3,11 @@
 
 import errno, os, sys, stat
 import re
-import smtplib
 import datetime, time
 import rpmUtils.miscutils
 from optparse import OptionParser
 import ConfigParser
+import Mailer, smtplib
 
 from PackageOwners import PackageOwners
 #from FakeOwners import FakeOwners as PackageOwners
@@ -108,29 +108,8 @@
 
 
 def mail(smtp, fromaddr, toaddrs, replytoaddr, subject, body):
-    from email.Header import Header
-    from email.MIMEText import MIMEText
-    msg = MIMEText( body, 'plain' )
-    from email.Utils import make_msgid
-    msg['Message-Id'] = make_msgid()
-    msg['Subject'] = Header(subject)
-    msg['From'] = Header(fromaddr)
-    from email.Utils import formatdate
-    msg['Date'] = formatdate()
-    if len(replytoaddr):
-        msg['Reply-To'] = Header(replytoaddr)
-
-    if isinstance(toaddrs, basestring):
-        toaddrs = [toaddrs]
-    to = ''
-    for t in toaddrs:
-        if len(to):
-            to += ', '
-        to += t
-    msg['To'] = Header(to)
-
     try:
-        r = smtp.sendmail( fromaddr, toaddrs, msg.as_string(False) )
+        r = smtp.sendmail( fromaddr, toaddrs, replytoaddr, subject, body )
         for (name, errormsg) in r.iteritems():
             print name, ':', errormsg
     except smtplib.SMTPRecipientsRefused, obj:
@@ -141,36 +120,6 @@
         print 'ERROR: SMTPException'
 
 
-def mailsplit(smtp, fromaddr, toaddrs, replytoaddr, subject, body):
-    # Split mail body at line positions to keep it below maxmailsize.
-    parts = 0
-    start = 0
-    end = len(body)
-    slices = []
-    while ( start < end ):
-        if ( (end-start) > Mail['maxsize'] ):
-            nextstart = body.rfind( '\n', start, start+Mail['maxsize'] )
-            if ( nextstart<0 or nextstart==start ):
-                print 'ERROR: cannot split mail body cleanly'
-                nextstart = end
-        else:
-            nextstart = end
-        slices.append( (start, nextstart) )
-        start = nextstart
-        parts += 1
-
-    curpart = 1
-    for (start,end) in slices:
-        if (parts>1):
-            subjectmodified = ( '(%d/%d) %s' % (curpart, parts, subject) )
-            time.sleep(1)
-        else:
-            subjectmodified = subject
-        slicedbody = body[start:end]
-        mail(smtp,fromaddr,toaddrs,replytoaddr,subjectmodified,slicedbody)
-        curpart += 1
-
-
 def loadConfigFile(filename):
     if not filename:
         return
@@ -418,17 +367,10 @@
 # Mail init.
 if domail:
     try:
-        srv = smtplib.SMTP( Mail['server'] )
-        #srv.set_debuglevel(1)
-        if (Mail['tls']):
-            srv.ehlo()
-            srv.starttls()
-            srv.ehlo()
-        if ( len(Mail['user']) and len(Mail['passwd']) ):
-            srv.login( Mail['user'], Mail['passwd'] )
+        srv = Mailer.Mailer( Mail['server'], Mail['user'], Mail['passwd'], Mail['tls'] )
+        srv.tryconnect()
     except smtplib.SMTPException, e:
-        print 'ERROR: mailserver login failed'
-        print e
+        print 'SMTPException:', e
         sys.exit(-1)
 
 # Mail reports to owners.
@@ -440,13 +382,15 @@
     mailtext += body
     if domail and ('owner' in opts.mail) and toaddr!='UNKNOWN OWNER':
         subject = Mail['subject'] + ' - %s' % datetime.date.today()
+        srv.maxmailsize = 0
         mail( srv, Mail['from'], toaddr, Mail['replyto'], subject, mailtext )
 
 # Mail summary to mailing-list.
 if domail and ('summary' in opts.mail):
     subject = Mail['subject'] + ' - %s' % datetime.date.today()
     toaddr = Mail['replyto']
-    mailsplit( srv, Mail['from'], toaddr, '', subject, summail )
+    srv.maxmailsize = Mail['maxsize']
+    mail( srv, Mail['from'], toaddr, '', subject, summail )
 
 if domail:
     srv.quit()




More information about the fedora-extras-commits mailing list