Exemplo n.º 1
0
    def sendExtendedIndividualMail( self, from_address, email, subject, message ):
        try:
            self.send_mail( email, subject, message, from_addr=from_address )

            return 1

        except smtplib.SMTPException:
            self.writeLog( FATAL_ERROR + " One or more fatal errors blocked sending of any e-mail from sendIndividulaMail(...) (using from address) with message >>>>\n" + str(message) + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
        except:
            self.writeLog( UNK_ERROR + " One or more fatal errors blocked sending of any e-mail with message >>>>\n" + str(message) + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
Exemplo n.º 2
0
    def sendRawMail( self, recepient , message ):
        try:
            self.send_mail( recepient, None, message )

            return 1

        except smtplib.SMTPException:
            self.writeLog( FATAL_ERROR + " One or more fatal errors blocked sending of any e-mail from sendRawMail(...)[two parameter] with message >>>>\n" + message + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
        
        except:
            self.writeLog( UNK_ERROR + " One or more fatal errors blocked sending of any e-mail with message >>>>\n" + message + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
Exemplo n.º 3
0
    def sendBatchMail( self, from_address, to_list, subject, message, cc_list=[], bcc_list=[], xheader=None ):
        """ Provides a means for doing batch sending
        of emails. """

        # require that all to, cc, and bcc are real python lists
        if type( to_list ) != type( [] )    \
           or type( cc_list ) != type( [] ) \
           or type( bcc_list ) != type( [] ):
            self.writeLog( FATA_ERROR + "hwMail.sendBatchMail used it to, cc, or bcc args that are not Python lists. No email sent." )
            return 0


        # create the cc string
        to_str = ''
        for addr in to_list:
            to_str = to_str + addr + ", "

        # remove the last comma
        if to_str != '':
            to_str = to_str[:-2]        

        # create the cc string
        cc_str = ''
        for addr in cc_list:
            cc_str = cc_str + addr + ", "

        # remove the last comma
        if cc_str != '':
            cc_str = cc_str[:-2]
        
        # combine the lists into a real to list
        to_list = to_list + cc_list + bcc_list


        try:
            # send the mail
            self.send_mail( to_list, subject, message, justCompile=FALSE, from_addr=from_address, to_string=to_str, cc_string=cc_str, xheader=xheader )

            return 1

        except smtplib.SMTPException:
            self.writeLog( FATAL_ERROR + " One or more fatal errors blocked sending of any e-mail from sendBatchMail(...) with message >>>>\n" + str(message) + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
        except:
            self.writeLog( UNK_ERROR + " One or more fatal errors blocked sending of any e-mail with message >>>>\n" + str(message) + "\n<<<<" )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
Exemplo n.º 4
0
    def flushErrorQueue( self, forceFlush=FALSE ):
        """ Attempts to send teh errored email. If attempts
        fail, and forceFlush is set to YES, then clears the
        queue regardless of the new attempt. """

        savedErrorQueue = []
        errorQueue =  self.load_error_queue( self.errorQueueFile  )
        
        if errorQueue != None:

            self.FLUSH_IN_PROGRESS = 1
            for email_tuple in errorQueue:
                
                # try to send the email
                ( from_addr, addrList, message ) = email_tuple

                result = 0
                try:
                    result = self.send_mail( addrList, None, message )
                except smtplib.SMTPException:
                    self.writeLog( FATAL_ERROR + " One or more fatal errors blocked sending of any e-mail from flushErrorQueue(...) with message >>>>\n" + str(message) + "\n<<<<" )
                    self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
                    result = 0
                except:
                    self.writeLog( UNK_ERROR + " One or more fatal errors blocked sending of any e-mail with message >>>>\n" + str(message) + "\n<<<<" )
                    self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
                    result = 0

                
                if result == 1:
                    self.writeLog( SUCCESS + " Sent mail to '%s' from the error queue."%( addrList ) ) 
                elif forceFlush != FALSE:
                    # remove from the list
                    self.writeLog( WARNING + " Could NOT send mail in error queue to '%s'; Force flush requested, removing mail from error queue."%( addrList ) )
                else:
                    self.writeLog( ERROR + " Could not send mail in the error queue; will retry on next load." )
                    savedErrorQueue.append( email_tuple )

            self.save_error_queue( self.errorQueueFile, savedErrorQueue )
            self.FLUSH_IN_PROGRESS = 0

            return 1
        else:
            self.writeLog( WARNING + " Could not use the error queue due to I/O problems." )
            self.FLUSH_IN_PROGRESS = 0
            return 0
Exemplo n.º 5
0
    def save_error_queue( self, errorQueueFile, errorQueue ):
        """Internal method for saving a queue to a file. Should
        not be called outside the method. """

        try:
            eqFile = open( errorQueueFile , "w" )
            cPickle.dump( errorQueue, eqFile )
            eqFile.close

            self.writeLog( "errorQueue = %s"%( errorQueue ) )

            self.writeLog( SUCCESS + " Saved error queue with '%d' stored e-mails to file."% ( len( errorQueue ) ) )

            return 1
        except:
            self.writeLog( WARNING + " Error occured while saving error queue file '%s'."%( self.errorQueueFile ) )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return 0
Exemplo n.º 6
0
    def load_error_queue( self, errorQueueFile ):
        """ Internal method for loading and retuning an
        error queue; should nto be called outside of the
        class. """

        try:

            errorQueue = []
            if os.path.isfile( errorQueueFile  ):
                eqFile = open( errorQueueFile , "r" )                
                errorQueue = cPickle.load( eqFile )
                eqFile.close()

            return errorQueue
            
        except:
            self.writeLog( WARNING + "while loading error queue file '%s'."%( self.errorQueueFile ) )
            self.writeLog( "STACK TRACE -> %s"%( hwStackTrace() ) )
            return None
Exemplo n.º 7
0
    def send_mail( self, addrList, subject, message, justCompile=FALSE, from_addr=None, to_string=None, cc_string=None, xheader=None ):
        
        # Add subject header to message
        #if subject != '':
        #    message = "Subject: " + subject + "\n\n" + message

        # Check to see if we are just compiling the message
        if justCompile != FALSE:
            return message


        # Attempt to send message by throtteling.
        # This is necessary to avoid conenction failures caused
        # by smtplib.

        self.numTimeouts = 0
        numAttempt = 0
        sent       = 0

        while sent == 0:
            try:
                #DEBUG
                #self.writeLog( "Entering loop." )

                # Create a connection to the SMTP server
                self.smtpServer.connect( self.confParser.get( self.server_sec, self.server_host ) )

                # DEBUG
                #self.writeLog( "Setting alarm." )
                
                # Set a timer
                signal.signal( signal.SIGALRM, self.timeOutHandler )
                signal.alarm( self.TIMEOUT )

                # DEBUG
                #self.writeLog( "Sending mail." )

                # set the from address if provided
                if from_addr == None:
                    from_addr = self.confParser.get( self.server_sec, self.from_addr )


                # create the propper string rep. of the to list
                if to_string == None or to_string == '':
                    if type( addrList ) == type( [] ):
                        to_string = ''
                        for addr in addrList:
                            to_string = to_string + str( addr ) + ", "

                        # remove the last comma
                        if to_string != '':
                            to_string = to_string[:-2]

                    else:
                        to_string = addrList


                # create cheader string
                xheader_string = ''
                if xheader != None and type(xheader) == type({}):
                    for key in xheader.keys():
                        xheader_string = "%s: %s\n"%( key , xheader[ key ] )  + xheader_string

                    # remove trailing new-line
                    xheader_string = xheader_string[:-1]

                    # add a new line at the head
                    xheader_string = "\n" + xheader_string


                # Edit message to provide sender's To: address
                if subject == None:
                    # this is a raw e-mail, do nothing
                    pass
                elif cc_string == None or cc_string == '':
                    message = "From: %s\nTo: %s\nSubject: %s%s\n\n%s"%( from_addr, to_string, subject, xheader_string, message )
                else:
                    message = "From: %s\nTo: %s\nCc: %s\nSubject: %s%s\n\n%s"%( from_addr, to_string, cc_string, subject, xheader_string, message )


                #self.writeLog( "message -> %s" %( message ) )


                # Send the e-mail
                resultDict = self.smtpServer.sendmail( from_addr, addrList, message )

                #DEBUG
                #self.writeLog( "Resetting alarm after success." )
                
                # Reset the alarm
                signal.alarm( 0 )

                # Check if we did not send mail cleanly
                if numAttempt > 0 or self.numTimeouts > 0:
                    self.writeLog( RESOLVED + " exception on attempt '%d'; mail sent to: %s" %(numAttempt, addrList) )
                else:
                    self.writeLog( SUCCESS + " successfully sent mail to: %s" %(addrList) )
        
                # If any e-mail was undilivered
                for key in resultDict.keys():
                    self.writeLog( WARNING + " Recepient '" + str( resultDict[ key ] ) + "' did not receive an e-mail!" )


                self.smtpServer.quit()
                sent = 1

                #DEBUG
                #self.writeLog( "Quit server and set sent to %d" %(sent) )


            except timeoutException :
                signal.alarm( 0 )
                self.writeLog( WARNING + " timeout occured on attempt '%d' to address '%s'. Trying to send again." %(self.numTimeouts, str(addrList)) )
                

            except :
                # We catch all exceptions that are raised. If the exception is
                # well known (par tof the list in the if clause below) then the
                # the error is bubbled up to the calling method. Otherwise,
                # we attempt to send the mail up the maximum attempt count.
                
                
                signal.alarm( 0 )

                self.writeLog( ERROR + " exception '%s' with value '%s' occured while sending mail." %(sys.exc_info()[0] , sys.exc_info()[1] ) )

                self.writeLog( "Stack trace -> " + hwStackTrace() )

                if sys.exc_info()[0] not in [ fatalTimeoutException, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPDataError ]:
                    
                    numAttempt = numAttempt + 1
                    
                    self.writeLog( WARNING + " failed to send on error attempt no. '%d' to address '%s'." %(numAttempt, str(addrList)) )

                    # If we tried this three time, it is going to fails
                    if numAttempt == self.MAX_NUM_ATTEMPTS:
                        self.writeLog( FATAL_ERROR + " after making '%d' attempts to send mail to address '%s'; mail NOT sent." %(numAttempt, addrList) )

                        self.addToErrorQueue( [ from_addr, addrList, message ] )
                        
                        self.smtpServer.quit()                        
                        raise

                    # Sleep a time exponential to 
                    time.sleep( 2 + numAttempt*3 )

                else:
                    self.addToErrorQueue( [ from_addr, addrList, message ] )
                    
                    self.writeLog( FATAL_ERROR + " exception '%s' with value '%s' while sending mail to address '%s'; mail NOT sent." %( sys.exc_info()[0], sys.exc_info()[1], str(addrList) ) ) 
                    self.smtpServer.quit()
                    raise