Beispiel #1
0
 def onShowMySource(self, showAsMail=False):
     """
     display my sourcecode file, plus imported modules here & elsewhere
     """
     import PyMailGui, ListWindows, ViewWindows, SharedNames, textConfig
     from PP4E.Internet.Email.mailtools import (  # mailtools now a pkg
         mailSender, mailFetcher, mailParser)  # can't use * in def
     mymods = (PyMailGui, ListWindows, ViewWindows, SharedNames,
               PyMailGuiHelp, popuputil, messagecache, wraplines, html2text,
               mailtools, mailFetcher, mailSender, mailParser, mailconfig,
               textConfig, threadtools, windows, textEditor)
     for mod in mymods:
         source = mod.__file__
         if source.endswith('.pyc'):
             source = source[:-4] + '.py'  # assume a .py in same dir
         if showAsMail:
             # this is a bit cheesey...
             code = open(source).read()  # 3.0: platform encoding
             user = mailconfig.myaddress
             hdrmap = {'From': appname, 'To': user, 'Subject': mod.__name__}
             ViewWindow(showtext=code,
                        headermap=hdrmap,
                        origmessage=email.message.Message())
         else:
             # more useful PyEdit text editor
             # 4E: assume in UTF8 Unicode encoding (else PeEdit may ask!)
             wintitle = ' - ' + mod.__name__
             textEditor.TextEditorMainPopup(self, source, wintitle, 'utf-8')
Beispiel #2
0
    def contViewFmt(self, msgnums):
        for msgnum in msgnums:
            fulltext = self.getMessage(msgnum)
            message = self.parseMessage(fulltext)
            type, content = self.findMainText(message)
            content = wraplines.wrapText1(content, mailconfig.wrapsz)
            ViewWindow(headermap=message,
                       showtext=content,
                       origmessage=message)

            # non-multipart, content-type text/html (rude but true!)
            # can also be opened manually from Split or part button
            # if non-multipart, other: must open part manually with
            # Split or part button; no verify if mailconfig says so;

            if type == 'text/html':
                if ((not mailconfig.verifyHTMLTextOpen)
                        or askyesno(appname, 'Open message text in browser?')):
                    try:
                        from tempfile import gettempdir  # or a Tk html viewer?
                        tempname = os.path.join(gettempdir(), 'pymailgui.html')
                        open(tempname, 'w').write(content)
                        webbrowser.open_new('file://' + tempname)
                    except:
                        show_error(appname, 'Cannot open in browser')
Beispiel #3
0
    def contViewFmt(self, msgnums):
        for msgnum in msgnums:
            fulltext = self.getMessage(msgnum)
            message = self.parseMessage(fulltext)
            type, content = self.findMainText(message)
            if type in ['text/html', 'text/xml']:
                content = html2text.html2text(content)
            content = wraplines.wrapText1(content, mailconfig.wrapsz)
            ViewWindow(headermap=message,
                       showtext=content,
                       origmessage=message)
            # non-multipart content-type text/HTML
            if type == 'text/html':
                if ((not mailconfig.verifyHTMLTextOpen)
                        or askyesno(appname, 'Open message text in browser?')):

                    type, asbytes = self.findMainText(message, asStr=False)
                    try:
                        from tempfile import gettempdir
                        tempname = os.path.join(gettempdir(), 'pymailgui.html')
                        tmp = open(tempname, 'wb')
                        tmp.write(asbytes)
                        webbrowser.open_new('file://' + tempname)

                    except:
                        showerror(appname, 'Cannot open in browser')
Beispiel #4
0
	def onShowMySource(self, showAsMail=False):
		"""
		отображает файлы с исходными текстами плюс
		импортирует модули кое-где
		"""
		import PyMailGui, ListWindows, ViewWindows, SharedNames, textConfig
		from Tom2.ch13.mailtools import (mailSender, mailFetcher, mailParser)
		# FIXME ??? возможны проблемы с mailconfig
		mymods = (
			PyMailGui, ListWindows, ViewWindows, SharedNames,
			PyMailGuiHelp, popuputil, messagecache, wraplines, html2text,
			mailtools, mailFetcher, mailSender, mailParser,
			mailconfig, textConfig, threadtools, windows, textEditor
		)
		for mod in mymods:
			source = mod.__file__
			if source.endswith('.pyc'):
				source = source[:-4] + '.py'						# предполагается присутствие файлов .py в том же каталоге
			if showAsMail:
				# не очень элегантно...
				code = open(source).read()							# 3.0: кодировка для платформы
				user = mailconfig.myaddress
				hdrmap = {'From': appname, 'To': user, 'Subject': mod.__name__}
				ViewWindow( showtext = code,
							headermap = hdrmap,
							origmessage = email.message.Message())
			else:
				# более удобный текстовый редактор PyEdit
				# 4E: предполагается, что текст в кодировке UTF8
				# (иначе PyEdit может запросить кодировку!)
				wintitle = ' - ' + mod.__name__
				textEditor.TextEditorMainPopup(self, source, wintitle, 'utf-8')
Beispiel #5
0
    def contViewFmt(self, msgnums):
        """
        finish View: extract main text, popup view window(s) to display;
        extracts plain text from html text if required, wraps text lines;
        html mails: show extracted text, then save in temp file and open
        in web browser;  part can also be opened manually from view window
        Split or part button;  if non-multipart, other: part must be opened
        manually with Split or part button;  verify html open per mailconfig;

        3.0: for html-only mails, main text is str here, but save its raw
        bytes in binary mode to finesse encodings;  worth the effort because 
        many mails are just html today;  this first tried N encoding guesses 
        (utf-8, latin-1, platform dflt), but now gets and saves raw bytes to
        minimize any fidelity loss;  if a part is later opened on demand, it 
        is saved in a binary file as raw bytes in the same way;

        caveat: the spawned web browser won't have any original email headers:
        it may still have to guess or be told the encoding, unless the html 
        already has its own encoding headers (these take the form of <meta>
        html tags within <head> sections if present; none are inserted in the 
        html here, as some well-formed html parts have them);  IE seems to 
        handle most html part files anyhow;  always encoding html parts to 
        utf-8 may suffice too: this encoding can handle most types of text;  
        """
        for msgnum in msgnums:
            fulltext = self.getMessage(msgnum)  # 3.0: str for parser
            message = self.parseMessage(fulltext)
            type, content = self.findMainText(message)  # 3.0: Unicode decoded
            if type in ['text/html', 'text/xml']:  # 3.0: get plain text
                content = html2text.html2text(content)
            content = wraplines.wrapText1(content, mailconfig.wrapsz)
            ViewWindow(headermap=message,
                       showtext=content,
                       origmessage=message)  # 3.0: decodes headers

            # non-multipart, content-type text/HTML (rude but true!)
            if type == 'text/html':
                if ((not mailconfig.verifyHTMLTextOpen)
                        or askyesno(appname, 'Open message text in browser?')):

                    # 3.0: get post mime decode, pre unicode decode bytes
                    type, asbytes = self.findMainText(message, asStr=False)
                    try:
                        from tempfile import gettempdir  # or a Tk HTML viewer?
                        tempname = os.path.join(gettempdir(), 'pymailgui.html')
                        tmp = open(tempname, 'wb')  # already encoded
                        tmp.write(asbytes)
                        tmp.close()  # flush output now
                        webbrowser.open_new('file://' + tempname)
                    except:
                        showerror(appname, 'Cannot open in browser')
Beispiel #6
0
	def contViewFmt(self, msgnums):
		"""
		завершение операции вывода окна просмотра: извлекает основной текст,
		выводит окно (окна) для отображения; если необходимо, извлекает
		простой текст из html, выполняет перенос строк; сообщения в формате
		html: выводит извлеченный текст, затем сохраняет во временном файле
		и открывает в веб-браузере; части сообщений могут также открываться
		вручную из окна просмотра с помощью кнопки Split (Разбить)
		или кнопок быстрого доступа к вложениями; в сообщении, состоящем
		из единственной части, иначе: часть должна открываться вручную
		кнопкой Split (Разбить) или кнопкой быстрого доступа к части;
		проверяет необходимость открытия html в mailconfig;

		3.0: для сообщений, содержащих только разметку html, основной текст
		здесь имеет тип str, но сохраняется он в двоичном режиме, чтобы
		обойти проблемы с кодировками; это необходимо, потому что
		значительная часть электронных писем в настоящее время
		отправляется в формате html; в первых версиях делалась попытка
		подобрать кодировку и N возможных (utf-8, latin-1, по умолчанию
		для платформы), но теперь тело сообщения получается и сохраняется
		в двоичном виде, чтобы минимизировать любые потери точности;
		если позднее часть будет открываться по требованию, она точно
		так же будет сохранена в файл в двоичном режиме;

		предупреждение: запускаемый веб-браузер не получает оригинальные
		заголовки письма: ему, вероятно, придется строить свои догадки
		о кодировке или вам придется явно сообщать ему о кодировке, если
		в разметке html отсутствуют собственные заголовки с информацией
		о кодировке (они принимают форму тегов <meta> в разделе <head>,
		если таковой имеется; здесь ничего не вставляется в разметку html,
		так как некоторые корректно оформленные части в формате html уже
		имеют все необходимое); IE, похоже, способен обработать большинство
		файлов html; кодирования частей html в utf-8 также может оказаться
		вполне достаточным: эта кодировка может с успехом применяться
		к большинству типов текста;
		"""
		for msgnum in msgnums:
			fulltext = self.getMessage(msgnum)				# 3.0: str для анализа
			self.trace('---contViewFmt->')
			self.trace(str(fulltext))
			message = self.parseMessage(fulltext)
			ctype, content = self.findMainText(message)		# 3.0: декодированный Юникод
			if ctype in ['text/html', 'text/xml']:			# 3.0: извлечь текст
				content = html2text.html2text(content)
			content = wraplines.wrapText1(content, mailconfig.wrapsz)
			ViewWindow(headermap   = message,
					   showtext    = content,
					   origmessage = message)				# 3.0: декодирует заголовки

			# единственная часть, content-type text/HTML (грубо, но верно!)
			if ctype == 'text/html':
				if ((not mailconfig.verifyHTMLTextOpen) or
					askyesno(appname, 'Open message text in browser?')):
					# 3.0: перед декодированием в Юникод преобразовать из формата MIME
					ctype, asbytes = self.findMainText(message, asStr=False)
					try:
						from tempfile import gettempdir		# или виджет Тк
						tempname = os.path.join(gettempdir(),
												'pymailgui.html')
						tmp = open(tempname, 'wb')
						# FIXME ???
						tmp.close()
						tmp.write(asbytes)
						webbrowser.open_new('file://' + tempname)
					except:
						showerror(appname, 'Cannot open in browser')