import os from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email import encoders import smtplib import types import RS.Config SUPPORTED_TEXT_ATTACHMENTS = [ 'xml', 'ulog', 'txt', 'ms', 'py', 'ini', 'log' ] SUPPORTED_IMAGE_ATTACHMENTS = [ 'png', 'tga', 'jpg', 'bmp' ] def Send( emailFrom, emailTo, emailSubject, emailBody, asHtml = False, attachments = [] ): ''' Sends an email using the exchange server found in the project module. ''' global SUPPORTED_IMAGE_ATTACHMENTS global SUPPORTED_TEXT_ATTACHMENTS toStr = '' if not type( emailTo ) == types.ListType and not type( emailTo ) == types.TupleType: emailTo = [ emailTo ] for emailAddress in emailTo: toStr += emailAddress + ';' message = MIMEMultipart( 'alternative' ) message[ 'Subject' ] = '{0}'.format( emailSubject ) message[ 'To' ] = toStr message[ 'From' ] = emailFrom if asHtml: body = MIMEText( emailBody, 'html' ) else: body = MIMEText( emailBody ) message.attach( body ) for attachment in attachments: if os.path.isfile( attachment ): fileType = str( attachment ).split( '.' )[ -1 ].lower() if fileType in SUPPORTED_TEXT_ATTACHMENTS: part = MIMEBase( 'application', 'octet-stream' ) part.set_payload( open( attachment, 'r' ).read() ) encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename={0}'.format( os.path.basename( attachment ) ) ) message.attach( part ) elif fileType in SUPPORTED_IMAGE_ATTACHMENTS: part = MIMEBase( 'application', 'octet-stream' ) part.set_payload( open( attachment, 'rb' ).read() ) encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename={0}'.format( os.path.basename( attachment ) ) ) message.attach( part ) else: print 'The attachment file type ({0}) is not supported! You will need to add the file type as a supported type to this module.'.format( fileType ) else: print 'Could not attach file ({0}) because it does not exist!'.format( attachment ) try: server = smtplib.SMTP( RS.Config.User.ExchangeServer ) server.sendmail( emailFrom, emailTo, message.as_string() ) server.quit() except: print 'Could not send the email!'