# -*- coding: iso-8859-1 -*-#
#/usr/bin/env python
#Boa:Dialog:DialogError
import wx
import wx.lib.masked.textctrl

import os
import sys
import traceback
import platform
import __version__

# Import the email modules we'll need
from email import Encoders
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Generator import Generator
import smtplib

import simplemapi

# definitions for error handling dialog
eMailSubject = 'A problem report for "MyApp"'
eMailToAddr = 'support@MyApp.com'


def create(parent):
    return DialogError(parent)

[wxID_DIALOGERROR, wxID_DIALOGERRORCANCEL, wxID_DIALOGERRORCLEAR, 
 wxID_DIALOGERRORCONTEXTHELPBUTTON1, wxID_DIALOGERROREMAIL, 
 wxID_DIALOGERRORINFOMSG, wxID_DIALOGERRORMESSAGE, wxID_DIALOGERRORSEND, 
 wxID_DIALOGERRORSENDMAPI, wxID_DIALOGERRORSMTPAUTH, 
 wxID_DIALOGERRORSMTPPASSWORD, wxID_DIALOGERRORSMTPSERVER, 
 wxID_DIALOGERRORSMTPUSER, wxID_DIALOGERRORSQLLOG, 
 wxID_DIALOGERRORSTATICLINE1, wxID_DIALOGERRORSTATUSBAR, 
 wxID_DIALOGERRORSTDERRLOG, wxID_DIALOGERRORSTDOUTLOG, 
 wxID_DIALOGERRORSTEMAIL, wxID_DIALOGERRORSTERRLOG, wxID_DIALOGERRORSTMESSAGE, 
 wxID_DIALOGERRORSTPASSWORD, wxID_DIALOGERRORSTSMTPSERVER, 
 wxID_DIALOGERRORSTSMTPUSER, wxID_DIALOGERRORSTSQLLOG, 
 wxID_DIALOGERRORSTSTDLOG, 
] = [wx.NewId() for _init_ctrls in range(26)]

class DialogError(wx.Dialog):
    def _init_coll_bsPage_Items(self, parent):
        # generated method, don't edit

        parent.AddSizer(self.fgsmsg, 3, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.staticLine1, 0, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddSizer(self.fgsOther, 0, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.infoMsg, 0, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddSizer(self.fgsButtons, 0, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.statusBar, 0, border=2, flag=wx.ALL | wx.EXPAND)

    def _init_coll_fgsmsg_Items(self, parent):
        # generated method, don't edit

        parent.AddWindow(self.stMessage, 1, border=2,
              flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.message, 1, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.stStdLog, 1, border=2,
              flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.stdoutlog, 1, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.stErrLog, 1, border=2,
              flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.stderrlog, 1, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.stSqlLog, 1, border=2,
              flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.sqllog, 1, border=2, flag=wx.ALL | wx.EXPAND)

    def _init_coll_fgsOther_Items(self, parent):
        # generated method, don't edit

        parent.AddWindow(self.stEmail, 1, border=2,
              flag=wx.ADJUST_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.eMail, 0, border=2, flag=wx.ALL)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddWindow(self.stSMTPServer, 1, border=2,
              flag=wx.ADJUST_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.smtpServer, 0, border=2, flag=wx.ALL)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddWindow(self.smtpAuth, 0, border=2, flag=wx.ALL)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=0)
        parent.AddWindow(self.stSMTPuser, 0, border=2,
              flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.smtpUser, 0, border=2, flag=wx.ALL | wx.EXPAND)
        parent.AddWindow(self.stPassword, 0, border=2,
              flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        parent.AddWindow(self.smtpPassword, 0, border=2,
              flag=wx.ALL | wx.EXPAND)

    def _init_coll_fgsButtons_Items(self, parent):
        # generated method, don't edit

        parent.AddWindow(self.send, 1, border=2, flag=wx.ALL)
        parent.AddWindow(self.sendMAPI, 1, border=2, flag=wx.ALL)
        parent.AddWindow(self.clear, 1, border=2, flag=wx.ALL)
        parent.AddWindow(self.cancel, 1, border=2, flag=wx.ALL)
        parent.AddSpacer(wx.Size(8, 8), border=0, flag=wx.ALL)
        parent.AddWindow(self.contextHelpButton1, 1, border=2, flag=wx.ALL)

    def _init_coll_fgsmsg_Growables(self, parent):
        # generated method, don't edit

        parent.AddGrowableRow(0)
        parent.AddGrowableRow(1)
        parent.AddGrowableRow(2)
        parent.AddGrowableRow(3)
        parent.AddGrowableCol(0)
        parent.AddGrowableCol(1)

    def _init_coll_statusBar_Fields(self, parent):
        # generated method, don't edit
        parent.SetFieldsCount(1)

        parent.SetStatusText(number=0, text='')

        parent.SetStatusWidths([-1])

    def _init_sizers(self):
        # generated method, don't edit
        self.bsPage = wx.BoxSizer(orient=wx.VERTICAL)

        self.fgsmsg = wx.FlexGridSizer(cols=2, hgap=0, rows=0, vgap=0)

        self.fgsOther = wx.FlexGridSizer(cols=4, hgap=0, rows=0, vgap=0)

        self.fgsButtons = wx.FlexGridSizer(cols=0, hgap=0, rows=1, vgap=0)

        self._init_coll_bsPage_Items(self.bsPage)
        self._init_coll_fgsmsg_Items(self.fgsmsg)
        self._init_coll_fgsmsg_Growables(self.fgsmsg)
        self._init_coll_fgsOther_Items(self.fgsOther)
        self._init_coll_fgsButtons_Items(self.fgsButtons)

        self.SetSizer(self.bsPage)

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOGERROR, name='DialogError',
              parent=prnt, pos=wx.Point(645, 213), size=wx.Size(846, 714),
              style=wx.DEFAULT_DIALOG_STYLE, title='Programming Error')
        self.SetClientSize(wx.Size(830, 678))
        self.Center(wx.BOTH)
        self.Bind(wx.EVT_CLOSE, self.OnDialogerrorClose)

        self.stMessage = wx.StaticText(id=wxID_DIALOGERRORSTMESSAGE,
              label='Message', name='stMessage', parent=self, pos=wx.Point(4,
              4), size=wx.Size(150, 51), style=0)

        self.message = wx.lib.masked.TextCtrl(id=wxID_DIALOGERRORMESSAGE,
              name='message', parent=self, pos=wx.Point(158, 4),
              size=wx.Size(668, 51), style=wx.TE_WORDWRAP | wx.TE_MULTILINE,
              value='')

        self.stStdLog = wx.StaticText(id=wxID_DIALOGERRORSTSTDLOG,
              label='Standard out log (display only):', name='stStdLog',
              parent=self, pos=wx.Point(4, 59), size=wx.Size(150, 180),
              style=0)

        self.stdoutlog = wx.TextCtrl(id=wxID_DIALOGERRORSTDOUTLOG,
              name='stdoutlog', parent=self, pos=wx.Point(158, 59),
              size=wx.Size(668, 180),
              style=wx.TE_READONLY | wx.TE_WORDWRAP | wx.TE_MULTILINE,
              value='')

        self.stErrLog = wx.StaticText(id=wxID_DIALOGERRORSTERRLOG,
              label='Standard error log (display only):', name='stErrLog',
              parent=self, pos=wx.Point(4, 243), size=wx.Size(150, 121),
              style=0)

        self.stderrlog = wx.TextCtrl(id=wxID_DIALOGERRORSTDERRLOG,
              name='stderrlog', parent=self, pos=wx.Point(158, 243),
              size=wx.Size(668, 121),
              style=wx.TE_READONLY | wx.TE_WORDWRAP | wx.TE_MULTILINE,
              value='')

        self.stSqlLog = wx.StaticText(id=wxID_DIALOGERRORSTSQLLOG,
              label='SQL log (display only):', name='stSqlLog', parent=self,
              pos=wx.Point(4, 368), size=wx.Size(150, 51), style=0)

        self.sqllog = wx.TextCtrl(id=wxID_DIALOGERRORSQLLOG, name='sqllog',
              parent=self, pos=wx.Point(158, 368), size=wx.Size(668, 51),
              style=wx.TE_READONLY | wx.TE_WORDWRAP | wx.TE_MULTILINE,
              value='')

        self.staticLine1 = wx.StaticLine(id=wxID_DIALOGERRORSTATICLINE1,
              name='staticLine1', parent=self, pos=wx.Point(2, 426),
              size=wx.Size(826, 2), style=0)

        self.stEmail = wx.StaticText(id=wxID_DIALOGERRORSTEMAIL,
              label='Your e-mail address:', name='stEmail', parent=self,
              pos=wx.Point(4, 438), size=wx.Size(95, 13), style=0)

        self.eMail = wx.lib.masked.TextCtrl(id=wxID_DIALOGERROREMAIL,
              name='eMail', parent=self, pos=wx.Point(161, 434),
              size=wx.Size(330, 22), style=0, value='')

        self.stSMTPServer = wx.StaticText(id=wxID_DIALOGERRORSTSMTPSERVER,
              label='Your SMTP server address:', name='stSMTPServer',
              parent=self, pos=wx.Point(4, 464), size=wx.Size(130, 13),
              style=0)

        self.smtpServer = wx.lib.masked.TextCtrl(id=wxID_DIALOGERRORSMTPSERVER,
              name='smtpServer', parent=self, pos=wx.Point(161, 460),
              size=wx.Size(330, 22), style=0, value='')

        self.smtpAuth = wx.CheckBox(id=wxID_DIALOGERRORSMTPAUTH,
              label='SMTP requires authorization', name='smtpAuth', parent=self,
              pos=wx.Point(4, 486), size=wx.Size(153, 13), style=0)
        self.smtpAuth.SetValue(False)
        self.smtpAuth.Bind(wx.EVT_CHECKBOX, self.OnSmtpAuthCheckbox,
              id=wxID_DIALOGERRORSMTPAUTH)

        self.stSMTPuser = wx.StaticText(id=wxID_DIALOGERRORSTSMTPUSER,
              label='SMTP user id', name='stSMTPuser', parent=self,
              pos=wx.Point(4, 507), size=wx.Size(61, 13), style=0)

        self.stPassword = wx.StaticText(id=wxID_DIALOGERRORSTPASSWORD,
              label='SMTP password', name='stPassword', parent=self,
              pos=wx.Point(495, 507), size=wx.Size(130, 13), style=0)

        self.smtpUser = wx.TextCtrl(id=wxID_DIALOGERRORSMTPUSER,
              name='smtpUser', parent=self, pos=wx.Point(161, 503),
              size=wx.Size(330, 21), style=0, value='')
        self.smtpUser.Enable(False)

        self.smtpPassword = wx.TextCtrl(id=wxID_DIALOGERRORSMTPPASSWORD,
              name='smtpPassword', parent=self, pos=wx.Point(629, 503),
              size=wx.Size(100, 21), style=wx.TE_PASSWORD, value='')
        self.smtpPassword.Enable(False)

        self.infoMsg = wx.TextCtrl(id=wxID_DIALOGERRORINFOMSG, name='infoMsg',
              parent=self, pos=wx.Point(2, 530), size=wx.Size(826, 88),
              style=wx.TE_MULTILINE | wx.TE_WORDWRAP | wx.TE_READONLY,
              value='')

        self.send = wx.Button(id=wxID_DIALOGERRORSEND, label='Send E-mail',
              name='send', parent=self, pos=wx.Point(4, 624), size=wx.Size(216,
              23), style=0)
        self.send.SetDefault()
        self.send.Bind(wx.EVT_BUTTON, self.OnSendButton,
              id=wxID_DIALOGERRORSEND)

        self.sendMAPI = wx.Button(id=wxID_DIALOGERRORSENDMAPI,
              label='Send using MAPI', name='sendMAPI', parent=self,
              pos=wx.Point(224, 624), size=wx.Size(216, 23), style=0)
        self.sendMAPI.Bind(wx.EVT_BUTTON, self.OnSendMAPIButton,
              id=wxID_DIALOGERRORSENDMAPI)

        self.cancel = wx.Button(id=wxID_DIALOGERRORCANCEL,
              label='Cancel and Close', name='close', parent=self,
              pos=wx.Point(662, 622), size=wx.Size(216, 23), style=0)
        self.cancel.Bind(wx.EVT_BUTTON, self.OnCancelButton,
              id=wxID_DIALOGERRORCANCEL)

        self.clear = wx.Button(id=wxID_DIALOGERRORCLEAR,
              label='Clear logs and Close', name='clear', parent=self,
              pos=wx.Point(444, 624), size=wx.Size(216, 23), style=0)
        self.clear.Bind(wx.EVT_BUTTON, self.OnClearButton,
              id=wxID_DIALOGERRORCLEAR)

        self.contextHelpButton1 = wx.ContextHelpButton(parent=self,
              pos=wx.Point(888, 624), size=wx.Size(20, 19),
              style=wx.BU_AUTODRAW)

        self.statusBar = wx.StatusBar(id=wxID_DIALOGERRORSTATUSBAR,
              name='statusBar', parent=self, style=0)
        self._init_coll_statusBar_Fields(self.statusBar)

        self._init_sizers()

    def __init__(self, parent):
        # None is passed as this is most often called from the wx.App
        self._init_ctrls(None)

        self.eMail.SetAutoformat('EMAIL')
        self.eMail.SetMask('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
        self.eMail.SetFormatcodes('F>')
        self.eMail.SetDescription('Email address')
        self.eMail.SetExcludeChars(' \\/*&%$#!+=\'"')
        self.eMail.SetValidRegex('^\\w+([\\-\\.]\\w+)*@((([a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*\\.)+)[a-zA-Z]{2,4}|\\[(\\d|\\d\\d|(1\\d\\d|2[0-4]\\d|25[0-5]))(\\.(\\d|\\d\\d|(1\\d\\d|2[0-4]\\d|25[0-5]))){3}\\]) *$')
        self.eMail.SetEmptyInvalid(True)

        self.smtpServer.SetEmptyInvalid(True)
        self.smtpServer.SetMask('X{50}')

        self.FixDefaultSize(self)
##        icon = myimages.getlogo32v1Icon()
##        self.SetIcon(icon)
        
        self.SetGetText()
        self.caller = parent
        
        self.msgtxt = self.caller.msg
        self.stdouttxt = self.caller.stdoutlog.read()
        self.stderrtxt = self.caller.stderrlog.read()
        self.sqllogtxt = self.caller.sqllog.read()

        self.message.WriteText(self.msgtxt)
        self.message.AppendText('\n\n') # some empty lines
        self.message.AppendText('Platform information:\n')
        self.message.AppendText(('System: %s\n') % platform.system())
        self.message.AppendText(('Release: %s\n') % platform.release())
        self.message.AppendText(('Version: %s\n') % platform.version())
        self.message.AppendText(('Machine: %s\n') % platform.machine())
        self.message.AppendText('Other:\n')
        self.message.AppendText(('Python version: %s, %s\n') % (platform.python_version(), platform.python_compiler()))
        self.message.AppendText(('wxPython version: %s\n') % wx.version())

        # db connection might not be available yet
        try:
            # getting license status from database
            #prefs = wx.GetApp().GetPrefs()
            #licenseYes = wx.GetApp().GetIt(prefs.owner, prefs.licensekey)
            licenseYes = True # fake the license status
            self.message.AppendText(('App version: %s-%s\n') % (__version__.appVERSION_STRING,
                                                             licenseYes))
        except:
            self.message.AppendText(('App version: %s-%s\n') % (__version__.appVERSION_STRING,
                                                                 'unknown'))
            
        self.message.AppendText('\n\n') # some empty lines
        
        self.stdoutlog.WriteText(self.stdouttxt)
        self.stderrlog.WriteText(self.stderrtxt)
        self.sqllog.WriteText(self.sqllogtxt)
        self.eMail.WriteText(self.caller.eMail)
        self.smtpServer.WriteText(self.caller.smtpServer)
        self.eMail.SetFocus()
        
        self.toaddr = eMailToAddr
        self.subject = eMailSubject
        
        self.Layout()

    def FixDefaultSize(self, window):
        if isinstance(window, wx.lib.masked.textctrl.TextCtrl):
            return
        window.SetMinSize(wx.DefaultSize)
        for child in window.GetChildren():
            self.FixDefaultSize(child)
        window.Layout()
        window.Refresh()

    def SetGetText(self):
        """Boa doesn't allow me to use _() directly, so I use SetLabel for
        each control to be translated, BUT this also has the advantage to be
        able to do dynamic switching of language by calling this function (not
        perfect as some controls don't allow setting labels after creation.
        """
        self.SetTitle(_('Programming error'))

        self.stMessage.SetLabel(_('Message'))
        self.message.SetToolTipString(_('Enter some additional information about the problem'))
        self.message.SetHelpText(_('Enter some additional information about the problem'))
        
        self.stStdLog.SetLabel(_('Standard out log (display only)'))
        self.stErrLog.SetLabel(_('Standard error log (display only)'))
        self.stSqlLog.SetLabel(_('SQL log (display only)'))

        self.stEmail.SetLabel(_('Your e-mail address'))
        self.eMail.SetToolTipString(_('Your e-mail address'))
        self.eMail.SetHelpText(_('Your e-mail address'))

        self.stSMTPServer.SetLabel(_('Your SMTPServer address'))
        self.smtpServer.SetToolTipString(_('Your SMTPServer address'))
        self.smtpServer.SetHelpText(_('Your SMTPServer address'))
        
        msgSMTP = _('A program error occured, please enter your e-mail address, your SMTP server name (e.g. smtp.free.fr), connect to the Internet and press the send e-mail button.')
        msgSMTP2 = _('If your SMTP server uses authorization enter the user id and password.')
        msgMAPI = _('Alternatively you can use the button "Send e-mail to support - MAPI" to send the email using your default email programme.')
        self.infoMsg.WriteText(msgSMTP + '\n\n' + msgSMTP2 + '\n\n' +msgMAPI)

        self.send.SetLabel(_('Send e-mail to support - SMTP'))
        self.send.SetToolTipString(_('Send e-mail to support - using SMTP server'))
        self.send.SetHelpText(_('Send e-mail to support - using SMTP server'))

        self.sendMAPI.SetLabel(_('Send e-mail to support - MAPI'))
        self.sendMAPI.SetToolTipString(_('Send e-mail to support - using MAPI'))
        self.sendMAPI.SetHelpText(_('Send e-mail to support - using MAPI'))
        
        self.clear.SetLabel(_('Clear logs and close dialog'))
        self.clear.SetToolTipString(_('Clear logs and close dialog.'))
        self.clear.SetHelpText(_('Clear logs and close dialog.'))

        self.cancel.SetLabel(_('Close dialog'))
        self.cancel.SetToolTipString(_('Close dialog - without clearing logs.'))
        self.cancel.SetHelpText(_('Close dialog - without clearing logs.'))

    def OnDialogerrorClose(self, event):
        event.Skip()

    def OnSendButton(self, event):
        self.statusBar.SetStatusText(number=0, text='')
        if not self.eMail.IsValid():
            self.statusBar.SetStatusText(number=0, text=_('Please enter a valid e-mail address'))
            return
        
        if not self.smtpServer.IsValid():
            self.statusBar.SetStatusText(number=0, text=_('Please enter a valid SMTP server address'))
            return

        self.caller.appConfig.Write(key='EMail', value=self.eMail.GetValue())
        self.caller.appConfig.Write(key='SMTPServer', value=self.smtpServer.GetValue())
        
        fromaddr, toaddr, mimemsg = self.PrepareMime()
        self.SendViaSMTP(fromaddr, toaddr, mimemsg)

    def PrepareMime(self):
        fromaddr = self.eMail.GetValue()
        
        mimemsg = MIMEMultipart()
        mimemsg['Subject'] = self.subject
        mimemsg['From'] = fromaddr
        mimemsg['To'] = self.toaddr
        mimemsg['CC'] = fromaddr
        mimemsg.preamble = self.subject
        mimemsg.epilogue = ''
    
        msg = MIMEText(self.message.GetValue())
        mimemsg.attach(msg)
        
        if len(self.stdouttxt) >0:
            stdout = MIMEText(self.stdouttxt)
            stdout.add_header('Content-Disposition', 'attachment', filename='stdout')
            mimemsg.attach(stdout)
            
        if len(self.stderrtxt) >0:
            stderr = MIMEText(self.stderrtxt)
            stderr.add_header('Content-Disposition', 'attachment', filename='stderr')
            mimemsg.attach(stderr)
            
        if len(self.sqllogtxt) >0:
            sqllog = MIMEText(self.sqllogtxt)
            sqllog.add_header('Content-Disposition', 'attachment', filename='sqllog')
            mimemsg.attach(sqllog)

        return fromaddr, self.toaddr, mimemsg

    def SendViaSMTP(self, fromaddr, toaddr, mimemsg):
        # Send the email via an SMTP server.
        try:
            s = smtplib.SMTP()
            s.connect(self.smtpServer.GetValue().strip())
            if self.smtpAuth.GetValue() == True:
                # login to server
                try:
                    s.login(self.smtpUser.GetValue(), self.smtpPassword.GetValue())
                except smtplib.SMTPAuthenticationError:
                    self.statusBar.SetStatusText(number=0, text=_('SMTP authentication failed'))
                    return
            s.sendmail(fromaddr, toaddr, mimemsg.as_string())
            s.close()
            self.send.Enable(False)
            self.ClearAllFiles()
            self.statusBar.SetStatusText(number=0, text=_('Report was sent to support - thank you.'))
    
        except smtplib.SMTPServerDisconnected:
            self.statusBar.SetStatusText(number=0, text=_('SMTP server disconnected'))
    
        except smtplib.SMTPSenderRefused:
            self.statusBar.SetStatusText(number=0, text=_('Email address problem "From"'))
    
        except smtplib.SMTPRecipientsRefused:
            self.statusBar.SetStatusText(number=0, text=_('Email address problem "To"'))
                
        except smtplib.SMTPDataError:
            self.statusBar.SetStatusText(number=0, text=_('Message data problem'))
            type, value, tb = sys.exc_info()
            for line in traceback.format_exception_only(type, value):
                print line
    
        except smtplib.SMTPConnectError:
            self.statusBar.SetStatusText(number=0, text=_('SMTP could not establish connection'))
            type, value, tb = sys.exc_info()
            for line in traceback.format_exception_only(type, value):
                print line
    
        except smtplib.socket.gaierror:
            self.statusBar.SetStatusText(number=0, text=_('SMTP server address problems - are you connected to the internet?'))
    
        except:
            self.statusBar.SetStatusText(number=0, text=_('SMTP - unknown error'))
            type, value, tb = sys.exc_info()
            for line in traceback.format_exception_only(type, value):
                print line

    def OnCancelButton(self, event):
        self.caller.appConfig.Write(key='EMail', value=self.eMail.GetValue())
        self.caller.appConfig.Write(key='SMTPServer', value=self.smtpServer.GetValue())
        self.Close()

    def OnClearButton(self, event):
        self.ClearAllFiles()
        self.Close()
        
    def ClearAllFiles(self):
        self.caller.sqllog.truncate(0)
        self.caller.stderrlog.truncate(0)
        self.caller.stdoutlog.truncate(0)

        self.caller.sqllog.seek(0)
        self.caller.stderrlog.seek(0)
        self.caller.stdoutlog.seek(0)

    def OnSendMAPIButton(self, event):
        self.statusBar.SetStatusText(number=0, text='')
        
        if platform.system() != 'Windows':
            self.statusBar.SetStatusText(number=0, text=_('Option only supported on Windows OS!'))
            return
        if not self.eMail.IsValid():
            self.statusBar.SetStatusText(number=0, text=_('Please enter a valid e-mail address'))
            return
        
        self.caller.appConfig.Write(key='EMail', value=self.eMail.GetValue())
        self.caller.appConfig.Write(key='SMTPServer', value=self.smtpServer.GetValue())
        # TODO: maybe update smtp auth stuff into config

        # simplemapi
        recipient = [(1, self.toaddr)]
        files = []

        if len(self.stdouttxt) >0:
            files.append(self.caller.stdoutlog.name)
        if len(self.stderrtxt) >0:
            files.append(self.caller.stderrlog.name)
        if len(self.sqllogtxt) >0:
            files.append(self.caller.sqllog.name)

        attachment = files
        subject = '%s' % self.subject
        body = '%s' % self.message.GetValue()

        try:
            simplemapi.SendMail(recipient, subject, body, attachment)
            self.sendMAPI.Enable(False)
            self.ClearAllFiles()
        except WindowsError, (errmsg, ):
            # ignore logon failure and abort errors
            if errmsg != 'MAPI error 3' and errmsg != 'MAPI error 1':
                raise

    def OnSmtpAuthCheckbox(self, event):
        obj = event.GetEventObject()
        if obj.GetValue() == True:
            self.smtpPassword.Enable(True)
            self.smtpUser.Enable(True)
        else:
            self.smtpPassword.Enable(False)
            self.smtpUser.Enable(False)
        event.Skip()
