Beispiel #1
0
	def __init__(self, parent, acc):
		self._acc = acc
		
		builder = Gtk.Builder()
		builder.set_translation_domain(PACKAGE_NAME)
		builder.add_from_file(get_data_file("account_dialog.ui"))
		builder.connect_signals({ \
			"account_type_changed" : self._on_cmb_account_type_changed, \
			"entry_changed" : self._on_entry_changed, \
			"btn_cancel_clicked" : self._on_btn_cancel_clicked, \
			"btn_save_clicked" : self._on_btn_save_clicked \
		})

		self._window = builder.get_object("account_dialog")
		self._window.set_transient_for(parent)

		self._cmb_account_type = builder.get_object("cmb_account_type")
		self._entry_account_name = builder.get_object("entry_account_name")
		self._entry_account_user = builder.get_object("entry_account_user")
		self._entry_account_password = builder.get_object("entry_account_password")
		self._entry_account_server = builder.get_object("entry_account_server")		
		self._entry_account_port = builder.get_object("entry_account_port")
		self._label_account_folder = builder.get_object("label_account_folder")
		self._entry_account_folder = builder.get_object("entry_account_folder")
		self._chk_account_push = builder.get_object("chk_account_push")
		self._chk_account_ssl = builder.get_object("chk_account_ssl")
		self._button_save = builder.get_object("button_save")

		self._entry_account_port.set_placeholder_text(_("optional"))
		self._entry_account_folder.set_placeholder_text(_("optional"))
Beispiel #2
0
 def set_default_connection(self, name):
     """Set default connection"""
     fconn = LPATH['CONNECTIONS'] + '/' + name
     if os.path.exists(fconn):
         self.app.config.set_value('Connection', 'default', name)
         self.log.debug(_("Connection '%s' set to default" % name))
     else:
         self.log.debug(_("Connection '%s' not available" % name))
         return None
Beispiel #3
0
	def _notify_count(self, count):
		if len(self._notifications) == 0:
			self._notifications['0'] = self._get_notification(" ", None, None) # empty string will emit a gtk warning
		
		if count > 1: # multiple new emails
			summary = _("You have {0} new mails.").format(str(count))
		else:
			summary = _("You have a new mail.")
		
		self._notifications['0'].update(summary, None, "mail-unread")
		self._notifications['0'].show()
Beispiel #4
0
    def get_connection(self, name):
        """Get connection data given its name"""
        config = ConfigParser()
        fconn = LPATH['CONNECTIONS'] + '/' + name
        if os.path.exists(fconn):
            connection =  {}
            config.read(fconn)
            connection['name'] = name
            connection['type'] = config.get('Connection', 'type')
            connection['data'] = config.get('Connection', 'data')
            self.log.debug(_("Got connection '%s' data" % name))

            return connection
        else:
            self.log.debug(_("Connection '%s' not available" % name))
            return None
Beispiel #5
0
 def close(self):
     try:
         self.do_commit()
         self.graph.close(True)
         self.log.debug( _("Graph closed"))
     except Exception, error:
         self.log.error(error)
Beispiel #6
0
	def notify_single(self, new_mails):
		for mail in new_mails:
			n = self.get_notification(mail.sender, mail.subject, "mail-unread")
			notification_id = str(id(n))
			n.add_action("mark-as-read", _("Mark as read"), self.__notification_action_handler, (mail, notification_id), None)			
			n.show()
			self.notifications[notification_id] = n
Beispiel #7
0
	def get_config_ui(self):
		box = Gtk.Box()
		box.set_spacing(12)
		box.set_orientation(Gtk.Orientation.VERTICAL)
		#box.set_size_request(100, -1)
		
		desc =  _('Mailnag will ignore mails containing at least one of \nthe following words in subject or sender.')
		
		label = Gtk.Label(desc)
		label.set_line_wrap(True)
		#label.set_size_request(100, -1);
		box.pack_start(label, False, False, 0)
		
		scrollwin = Gtk.ScrolledWindow()
		scrollwin.set_shadow_type(Gtk.ShadowType.IN)
		scrollwin.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		
		txtbuffer = Gtk.TextBuffer()
		txtview = Gtk.TextView()
		txtview.set_buffer(txtbuffer)
		txtview.set_wrap_mode(Gtk.WrapMode.WORD)
		
		scrollwin.add(txtview)
		
		box.pack_start(scrollwin, True, True, 0)
		
		return box
Beispiel #8
0
    def __init__(
        self,
        enabled=False,
        name=_("Unnamed"),
        user="",
        password="",
        server="",
        port="",
        ssl=True,
        imap=False,
        idle=False,
        folder="",
    ):

        self.enabled = enabled  # bool
        self.name = name
        self.user = user
        self.password = password
        self.server = server
        self.port = port
        self.ssl = ssl  # bool
        self.imap = imap  # bool
        self.idle = idle  # bool
        self.folder = folder
        self._conn = None
Beispiel #9
0
	def _get_header(self, msg_dict):
		try:
			content = self._get_header_field(msg_dict, 'From')
			sender = self._format_header_field('sender', content)
		except:
			sender = ('', '')

		try:
			content = self._get_header_field(msg_dict, 'Subject')
		except:
			content = _('No subject')
		try:
			subject = self._format_header_field('subject', content)
		except:
			subject = ''
		
		try:
			content = self._get_header_field(msg_dict, 'Date')
			datetime = self._format_header_field('date', content)
		except:
			logging.warning('Email date set to zero.')
			datetime = 0
			
		try:
			msgid = self._get_header_field(msg_dict, 'Message-ID')
		except:
			msgid = ''
		
		return (sender, subject, datetime, msgid)
Beispiel #10
0
    def create_connection(self, params):
        """Create a new connection"""
        session = create_session()
        try:
            cname = params[0] # Connection Name
            ctype = params[1] # Connection Type
            cdata = params[2] # Connection Extra Data
            if (cname and ctype and cdata):
                # FIXME: check params
                connection = {}
                connection['name'] = cname
                connection['type'] = ctype
                connection['data'] = cdata
                created = self.write_connection(connection)
                if created:
                    self.log.debug(_("Connection '%s' created" % cname))
                    session['rc'] = '0'
                    session['output'] = cname
                else:
                    session['rc'] = '-1'
                    session['output'] = "Connection '%s' could not be created." % cname
        except:
            session['rc'] = '-1'
            session['output'] = "Error. Connection '%s' could not be created." % cname

        return session
Beispiel #11
0
	def _load_config(self):
		self._entry_label.set_text(self._cfg.get('general', 'messagetray_label'))
		self._spinbutton_interval.set_value(int(self._cfg.get('general', 'check_interval')))
		self._cb_notification_mode.set_active(int(self._cfg.get('general', 'notification_mode')))
		self._chk_playsound.set_active(bool(int(self._cfg.get('general', 'playsound'))))
		self._chk_autostart.set_active(bool(int(self._cfg.get('general', 'autostart'))))

		
		self._chk_enable_filter.set_active(bool(int(self._cfg.get('filter', 'filter_enabled'))))
		self._textbuffer_filter.set_text(self._cfg.get('filter', 'filter_text'))

		self._chk_script0.set_active(bool(int(self._cfg.get('script', 'script0_enabled'))))
		
		tmp = self._cfg.get('script', 'script0_file')
		if len(tmp) > 0:
			self._filechooser_script0.set_filename(tmp)
		
		self._chk_script1.set_active(bool(int(self._cfg.get('script', 'script1_enabled'))))
		
		tmp = self._cfg.get('script', 'script1_file')
		if len(tmp) > 0:
			self._filechooser_script1.set_filename(tmp)
		
		self._accounts.load_from_cfg(self._cfg)
		
		if len(self._accounts) == 0:
			self._accounts.import_from_keyring()
			if len(self._accounts) > 0 and \
				(not self._show_yesno_dialog(_("Mailnag found %s mail accounts on this computer.\n\nDo you want to import them?") % len(self._accounts))):
				del self._accounts[:]

		for acc in self._accounts:
			row = [acc, acc.enabled, acc.name]
			self._liststore_accounts.append(row)
		self._select_path((0,))		
Beispiel #12
0
	def get_config_ui(self):
		box = Gtk.Box()
		box.set_spacing(12)
		box.set_orientation(Gtk.Orientation.VERTICAL)
		
		label = Gtk.Label()
		label.set_markup('<b>%s</b>' % _('Notification mode:'))
		label.set_alignment(0.0, 0.0)
		box.pack_start(label, False, False, 0)
		
		inner_box = Gtk.Box()
		inner_box.set_spacing(6)
		inner_box.set_orientation(Gtk.Orientation.VERTICAL)
		
		cb_count = Gtk.RadioButton(label = _('Count of new mails'))
		inner_box.pack_start(cb_count, False, False, 0)
		
		cb_summary = Gtk.RadioButton(label = _('Summary of new mails'), group = cb_count)
		inner_box.pack_start(cb_summary, False, False, 0)
		
		cb_single = Gtk.RadioButton(label = _('One notification per new mail'), group = cb_count)
		inner_box.pack_start(cb_single, False, False, 0)
		
		alignment = Gtk.Alignment()
		alignment.set_padding(0, 6, 18, 0)
		alignment.add(inner_box)
		box.pack_start(alignment, False, False, 0)
		
		label = Gtk.Label()
		label.set_markup('<b>%s</b>' % _('Maximum number of visible mails:'))
		label.set_alignment(0.0, 0.0)
		box.pack_start(label, False, False, 0)
		
		spinner = Gtk.SpinButton.new_with_range(1.0, MAX_VISIBLE_MAILS_LIMIT, 1.0)
		
		alignment = Gtk.Alignment()
		alignment.set_padding(0, 0, 18, 0)
		alignment.add(spinner)
		
		box.pack_start(alignment, False, False, 0)
		
		return box
Beispiel #13
0
    def __on_btn_remove_clicked(self, widget):
        acc, model, iter = self.get_selected_account()
        if iter != None:
            if self.show_yesno_dialog(_("Delete this account:") + "\n\n" + acc.name):

                p = model.get_path(iter)
                if not p.prev():
                    p.next()
                self.select_path(p)  # select prev/next account

                model.remove(iter)  # delete in treeview
                self.accounts.remove(acc)  # delete in accounts list
Beispiel #14
0
	def get_config_ui(self):
		box = Gtk.Box()
		box.set_spacing(12)
		box.set_orientation(Gtk.Orientation.VERTICAL)
		#box.set_size_request(100, -1)
		
		markup_str = "<i>&lt;%s&gt; &lt;%s&gt;</i>" % (_('sender'), _('subject'))
		desc =  _(	"The following script will be executed whenever new mails arrive.\n"
					"Mailnag passes the total count of new mails to this script,\n"
					"followed by %s pairs." % markup_str)
		
		label = Gtk.Label()
		label.set_line_wrap(True)
		label.set_markup(desc)
		#label.set_size_request(100, -1);
		box.pack_start(label, False, False, 0)
		
		filechooser = Gtk.FileChooserButton()
		box.pack_start(filechooser, True, True, 0)
		
		return box
Beispiel #15
0
	def _notify_single(self, mails):
		# In single notification mode new mails are
		# added to the *bottom* of the notification list.
		mails = sort_mails(mails, sort_desc = False)
		
		for mail in mails:
			n = self._get_notification(self._get_sender(mail), mail.subject, "mail-unread")
			notification_id = str(id(n))
			if self._is_gnome:
				n.add_action("mark-as-read", _("Mark as read"), 
					self._notification_action_handler, (mail, notification_id))			
			n.show()
			self._notifications[notification_id] = n
Beispiel #16
0
	def notify_summary(self, unseen_mails):
		summary = ""		
		body = ""

		if len(self.notifications) == 0:
			self.notifications['0'] = self.get_notification(" ", None, None) # empty string will emit a gtk warning
		
		ubound = len(unseen_mails) if len(unseen_mails) <= self.MAIL_LIST_LIMIT else self.MAIL_LIST_LIMIT
		
		for i in range(ubound):
			body += unseen_mails[i].sender + ":\n<i>" + unseen_mails[i].subject + "</i>\n\n"
		
		if len(unseen_mails) > self.MAIL_LIST_LIMIT:
			body += "<i>" + _("(and {0} more)").format(str(len(unseen_mails) - self.MAIL_LIST_LIMIT)) + "</i>"

		if len(unseen_mails) > 1: # multiple new emails
			summary = _("You have {0} new mails.").format(str(len(unseen_mails)))
		else:
			summary = _("You have a new mail.")

		self.notifications['0'].update(summary, body, "mail-unread")
		self.notifications['0'].show()
Beispiel #17
0
	def __init__(self, enabled = False, name = _('Unnamed'), user = '', \
		password = '', server = '', port = '', ssl = True, imap = False, idle = False, folder = '' ):
	
		self.enabled = enabled # bool
		self.name = name
		self.user = user
		self.password = password
		self.server = server
		self.port = port
		self.ssl = ssl # bool
		self.imap = imap # bool		
		self.idle = idle # bool
		self.folder = folder
Beispiel #18
0
 def stop_application(self, *args):
     """Stop Vazaar"""
     session = create_session()
     try:
         self.app.store.close()
         self.log.debug( _("Stopping Vazaar... see you later!") )
         loop = self.app.get_mainloop()
         loop.quit()
         session['rc'] = '0'
         session['output'] = ''
     except Exception, error:
         self.log.error(error)
         session['rc'] = '-1'
         session['output'] = ''
Beispiel #19
0
	def _fill_account_type_cmb(self):
		# fill acount type cmb
		for p in PROVIDER_CONFIGS:
			self._cmb_account_type.append_text(p[0])
		self._cmb_account_type.append_text(_("Other (IMAP)"))
		self._cmb_account_type.append_text(_("Other (POP3)"))
		
		# select account type
		if len(self._acc.server) == 0:
			# default to Gmail when creating new accounts
			self._cmb_account_type.set_active(IDX_GMAIL)
		else:
			i = 0
			idx = -1
			for p in PROVIDER_CONFIGS:
				if p[1] == self._acc.server:
					idx = i
					break
				i+=1
			
			if idx >= 0:
				self._cmb_account_type.set_active(idx)
			else:
				self._cmb_account_type.set_active(IDX_IMAP if self._acc.imap else IDX_POP3)
Beispiel #20
0
	def _notify_summary(self, new_mails, all_mails):
		summary = ""		
		body = ""
		
		# The mail list (all_mails) is sorted by date (mails with most recent 
		# date on top). New mails with no date or older mails that come in 
		# delayed won't be listed on top. So if a mail with no or an older date 
		# arrives, it gives the impression that the top most mail (i.e. the mail 
		# with the most recent date) is re-notified.
		# To fix that, simply put new mails on top explicitly.  
		mails = new_mails + [m for m in all_mails if m not in new_mails]
		
		if len(self._notifications) == 0:
			self._notifications['0'] = self._get_notification(" ", None, None) # empty string will emit a gtk warning

		ubound = len(mails) if len(mails) <= self._max_mails else self._max_mails

		for i in range(ubound):
			if self._is_gnome:
				body += "%s:\n<i>%s</i>\n\n" % (self._get_sender(mails[i]), mails[i].subject)
			else:
				body += "%s  -  %s\n" % (ellipsize(self._get_sender(mails[i]), 20), ellipsize(mails[i].subject, 20))

		if len(mails) > self._max_mails:
			if self._is_gnome:
				body += "<i>%s</i>" % _("(and {0} more)").format(str(len(mails) - self._max_mails))
			else:
				body += _("(and {0} more)").format(str(len(mails) - self._max_mails))

		if len(mails) > 1: # multiple new emails
			summary = _("You have {0} new mails.").format(str(len(mails)))
		else:
			summary = _("You have a new mail.")

		self._notifications['0'].update(summary, body, "mail-unread")
		self._notifications['0'].show()
Beispiel #21
0
	def _on_btn_remove_clicked(self, widget):
		acc, model, iter = self._get_selected_account()
		if iter != None:
			if self._show_yesno_dialog(_('Delete this account:') + \
				'\n\n' + acc.name):
				
				# select prev/next account
				p = model.get_path(iter)
				if not p.prev():
					p.next()
				self._select_path(p)
				
				# remove from treeview
				model.remove(iter)
				# remove from accounts list
				self._accounts.remove(acc)
Beispiel #22
0
 def write_connection(self, connection):
     """Write a new connection"""
     try:
         config = ConfigParser()
         config.add_section('Connection')
         config.set('Connection', 'type', connection['type'])
         config.set('Connection', 'data', connection['data'])
         filename = LPATH['CONNECTIONS'] + '/' + connection['name']
         fconn = open(filename, 'w')
         config.write(fconn)
         fconn.close()
         self.log.debug(_("Connection '%s' registered" % connection['name']))
         return True
     except Exception, error:
         self.log.error(error)
         return False
Beispiel #23
0
    def __init__(self, app):
        """This class manages real operations against a graph. This graph
        is defined by one connection (at time).

        By default StoreManager loads the default connection (if any). If
        no connection is defined the backend is not operative.

        Connections can be created at runtime by some frontend (GUI/CLI)
        """
        self.app = app
        self.app.settings['store'] = {}
        self.loglevel = self.app.get_logging_level()
        self.log = get_logger('Store', self.loglevel)
        self.conn = self.app.conn.get_default_connection()  # Default connection
        self.store = None   # Phisycal Store (sqlite, mysql, ...)
        self.graph = None   # RDF Graph (a ConjunctiveGraph)
        self.log.debug( _("StoreManager\tinitialized using '%s' connection" % self.conn) )
Beispiel #24
0
 def __init__(self, app):
     self.app = app
     self.graph = self.app.store.get_graph()
     self.loglevel = self.app.get_logging_level()
     self.log = get_logger('Ask', self.loglevel)
     self.log.debug( _("QueryManager\tinitialized") )
     self.total = 0
     self.cols = 0
     self.clipboard = 0
     self.notes = 0
     self.images = 0
     self.audio = 0
     self.video =  0
     self.text = 0
     self.apps = 0
     self.website = 0
     self.remote = 0
     self.feed = 0
     self.folder = 0
Beispiel #25
0
	def __init__(self):
		GLib.set_application_name('mailnag')
		self.was_locked = False											# True if Dialog shown. Required for Sortorder problem
		self.keyring_password = ''
		self.defaultKeyring = gnomekeyring.get_default_keyring_sync()
		if self.defaultKeyring == None:
			self.defaultKeyring = 'login'

		while gnomekeyring.get_info_sync(self.defaultKeyring).get_is_locked():		# Keyring locked?
			self.message_response = 'cancel'							# default response for message dialog
			try:
				try: gnomekeyring.unlock_sync(self.defaultKeyring, \
						self.keyring_password)
				except gnomekeyring.IOError:
					self.show_keyring_dialog()							# get keyring password
					Gtk.main()											# wait until dialog is closed
					result = gnomekeyring.unlock_sync(self.defaultKeyring, \
								self.keyring_password)
			except gnomekeyring.IOError:
				self.show_message(_('Failed to unlock Keyring "{0}".\nWrong password.\n\nDo you want to try again?').format(self.defaultKeyring))
				Gtk.main()												# wait until dialog is closed
				if self.message_response == 'cancel': exit(1)			# close application (else: continue getting password)
Beispiel #26
0
    def load_config(self):
        self.entry_label.set_text(self.cfg.get("general", "messagetray_label"))
        self.spinbutton_interval.set_value(int(self.cfg.get("general", "check_interval")))
        self.cb_notification_mode.set_active(int(self.cfg.get("general", "notification_mode")))
        self.chk_playsound.set_active(bool(int(self.cfg.get("general", "playsound"))))
        self.chk_autostart.set_active(bool(int(self.cfg.get("general", "autostart"))))

        self.chk_enable_filter.set_active(bool(int(self.cfg.get("filter", "filter_enabled"))))
        self.textbuffer_filter.set_text(self.cfg.get("filter", "filter_text"))

        self.chk_script0.set_active(bool(int(self.cfg.get("script", "script0_enabled"))))

        tmp = self.cfg.get("script", "script0_file")
        if len(tmp) > 0:
            self.filechooser_script0.set_filename(tmp)

        self.chk_script1.set_active(bool(int(self.cfg.get("script", "script1_enabled"))))

        tmp = self.cfg.get("script", "script1_file")
        if len(tmp) > 0:
            self.filechooser_script1.set_filename(tmp)

        self.accounts.load_from_cfg(self.cfg)

        if len(self.accounts) == 0:
            self.accounts.import_from_keyring()
            if len(self.accounts) > 0 and (
                not self.show_yesno_dialog(
                    _("Mailnag found %s mail accounts on this computer.\n\nDo you want to import them?")
                    % len(self.accounts)
                )
            ):
                del self.accounts[:]

        for acc in self.accounts:
            row = [acc, acc.enabled, acc.name]
            self.liststore_accounts.append(row)
        self.select_path((0,))
Beispiel #27
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#

import os
import xdg.BaseDirectory as bd
from ConfigParser import RawConfigParser
from common.i18n import _

mailnag_defaults = {
	'general':
	{
		'messagetray_label'	: _('New email'),
		'check_interval'	: '5',
		'notification_mode'	: '0',
		'sender_format'		: '1',
		'playsound'			: '1',
		'soundfile'			: 'mailnag.ogg',
		'autostart'			: '1'
	},
	'filter':
	{
		'filter_enabled'	: '0',
		'filter_text'		: 'newsletter, viagra'
	},
	'script':
	{
		'script0_enabled'	: '0',
Beispiel #28
0
	def get_mail(self, sort_order = None):
		mail_list = []
		mail_ids = []
		
		filter_enabled = bool(int(self._cfg.get('filter', 'filter_enabled')))

		for acc in self._accounts:
			# get server connection for this account
			srv = acc.get_connection(use_existing = True)
			if srv == None:
				continue
			elif acc.imap:# IMAP
				if len(acc.folder.strip()) == 0:
					folder_list = ["INBOX"]
				else:
					folder_list = acc.folder.split(',')
					
				for folder in folder_list:	
					folder = folder.strip()
					if len(folder) == 0:
						continue
					
					# select IMAP folder
					srv.select(folder, readonly=True)
					try:
						status, data = srv.search(None, 'UNSEEN') # ALL or UNSEEN
					except:
						print "The folder:", folder, "does not exist, using INBOX instead"
						try:
							# if search fails select INBOX and try again
							srv.select('INBOX', readonly=True)
							status, data = srv.search(None, 'UNSEEN') # ALL or UNSEEN
						except:
							print "INBOX Could not be found", sys.exc_info()[0]

					if status != 'OK' or None in [d for d in data]:
						print "Folder", folder, "in status", status, "| Data:", data, "\n"
						continue # Bugfix LP-735071
					for num in data[0].split():
						typ, msg_data = srv.fetch(num, '(BODY.PEEK[HEADER])') # header only (without setting READ flag)
						for response_part in msg_data:
							if isinstance(response_part, tuple):
								try:
									msg = email.message_from_string(response_part[1])
								except:
									print "Could not get IMAP message." # debug
									continue
								try:
									try:
										# get sender and format it
										sender = self._format_header('sender', msg['From'])
									except KeyError:
										print "KeyError exception for key 'From' in message." # debug
										sender = self._format_header('sender', msg['from'])
								except:
									print "Could not get sender from IMAP message." # debug
									sender = "Error in sender"
								try:
									try:
										# get date and format it
										datetime, seconds = self._format_header('date', msg['Date'])
									except KeyError:
										print "KeyError exception for key 'Date' in message." # debug
										datetime, seconds = self._format_header('date', msg['date'])
								except:
									print "Could not get date from IMAP message." # debug
									# take current time as "2010.12.31 13:57:04"
									datetime = time.strftime('%Y.%m.%d %X')
									# current time to seconds
									seconds = time.time()
								try:
									try:
										# get subject and format it
										subject = self._format_header('subject', msg['Subject'])
									except KeyError:
										print "KeyError exception for key 'Subject' in message." # debug
										subject = self._format_header('subject', msg['subject'])
								except:
									print "Could not get subject from IMAP message." # debug
									subject = _('No subject')
								try:
									id = msg['Message-Id']
								except:
									print "Could not get id from IMAP message."	# debug
									id = None
							
								if id == None or id == '':
									# create fallback id
									id = str(hash(acc.server + acc.user + sender + subject))
					
						# prevent duplicates caused by Gmail labels
						if id not in mail_ids:
							if not (filter_enabled and self._in_filter(sender + subject)): # check filter
								mail_list.append(Mail(seconds, subject, \
									sender, datetime, id, acc.get_id()))
								mail_ids.append(id)
				
				# don't close IMAP idle connections
				if not acc.idle:
					srv.close()
					srv.logout()
			else: # POP
				# number of mails on the server
				mail_total = len(srv.list()[1])
				for i in range(1, mail_total+1): # for each mail
					try:
						# header plus first 0 lines from body
						message = srv.top(i, 0)[1]
					except:
						print "Could not get POP message." # debug
						continue
					
					# convert list to string
					message_string = '\n'.join(message)
					
					try:
						# put message into email object and make a dictionary
						msg = dict(email.message_from_string(message_string))
					except:
						print "Could not get msg from POP message."	# debug
						continue
					try:
						try:
							# get sender and format it
							sender = self._format_header('sender', msg['From'])
						except KeyError:
							print "KeyError exception for key 'From' in message." # debug
							sender = self._format_header('sender', msg['from'])
					except:
						print "Could not get sender from POP message." # debug
						sender = "Error in sender"
					try:
						try:
							# get date and format it
							datetime, seconds = self._format_header('date', msg['Date'])
						except KeyError:
							print "KeyError exception for key 'Date' in message." # debug
							datetime, seconds = self._format_header('date', msg['date'])
					except:
						print "Could not get date from POP message." # debug
						# take current time as "2010.12.31 13:57:04"
						datetime = time.strftime('%Y.%m.%d %X')
						# current time to seconds
						seconds = time.time()
					try:
						try:
							# get subject and format it
							subject = self._format_header('subject', msg['Subject'])
						except KeyError:
							print "KeyError exception for key 'Subject' in message." # debug
							subject = self._format_header('subject', msg['subject'])
					except:
						print "Could not get subject from POP message."
						subject = _('No subject')
					try:
						# get id
						uidl = srv.uidl(i)
					except:
						print "Could not get id from POP message." # debug
						uidl = None
					
					if uidl == None or uidl == '':
						# create fallback id
						id = str(hash(acc.server + acc.user + sender + subject))
					else:
						# create unique id
						id = acc.user + uidl.split(' ')[2]
					
					if not (filter_enabled and self._in_filter(sender + subject)): # check filter
						mail_list.append(Mail(seconds, subject, sender, \
							datetime, id, acc.get_id()))

				# disconnect from Email-Server
				srv.quit()
		
		if (sort_order != None):
			# sort mails
			mail_list = self.sort_mails(mail_list, sort_order)
		
		# write stdout to log file
		sys.stdout.flush()
		return mail_list
Beispiel #29
0
	def get_manifest(self):
		return (_("Spam Filter"),
				_("Filters out unwanted mails."),
				"1.0",
				"Patrick Ulbrich <*****@*****.**>",
				False)
Beispiel #30
0
    def __init__(self):
        builder = Gtk.Builder()
        builder.set_translation_domain(PACKAGE_NAME)
        builder.add_from_file(get_data_file("config_window.ui"))
        builder.connect_signals(
            {
                "config_window_deleted": self.__on_config_window_deleted,
                "btn_add_clicked": self.__on_btn_add_clicked,
                "btn_edit_clicked": self.__on_btn_edit_clicked,
                "btn_remove_clicked": self.__on_btn_remove_clicked,
                "treeview_accounts_row_activated": self.__on_treeview_accounts_row_activated,
                "liststore_accounts_row_deleted": self.__on_liststore_accounts_row_deleted,
                "liststore_accounts_row_inserted": self.__on_liststore_accounts_row_inserted,
                "chk_enable_filter_toggled": self.__on_chk_enable_filter_toggled,
                "chk_script0_toggled": self.__on_chk_script0_toggled,
                "chk_script1_toggled": self.__on_chk_script1_toggled,
            }
        )

        self.window = builder.get_object("config_window")
        self.window.set_icon(GdkPixbuf.Pixbuf.new_from_file_at_size(get_data_file("mailnag.svg"), 48, 48))
        self.cfg = read_cfg()

        #
        # account tab
        #
        self.accounts = AccountList()

        self.treeview_accounts = builder.get_object("treeview_accounts")
        self.liststore_accounts = builder.get_object("liststore_accounts")

        self.button_edit = builder.get_object("button_edit")
        self.button_remove = builder.get_object("button_remove")

        renderer_on = Gtk.CellRendererToggle()
        renderer_on.connect("toggled", self.__on_account_toggled)  # bind toggle signal
        column_on = Gtk.TreeViewColumn(_("Enabled"), renderer_on)  # Account On/Off
        column_on.add_attribute(renderer_on, "active", 1)
        column_on.set_alignment(0.5)  # center column heading
        self.treeview_accounts.append_column(column_on)

        renderer_name = Gtk.CellRendererText()
        column_name = Gtk.TreeViewColumn(_("Name"), renderer_name, text=2)  # Account Name
        self.treeview_accounts.append_column(column_name)

        #
        # general tab
        #
        self.entry_label = builder.get_object("entry_label")
        self.spinbutton_interval = builder.get_object("spinbutton_interval")
        self.cb_notification_mode = builder.get_object("cb_notification_mode")
        cell = Gtk.CellRendererText()
        self.cb_notification_mode.pack_start(cell, True)
        self.cb_notification_mode.add_attribute(cell, "text", 0)
        self.chk_playsound = builder.get_object("chk_playsound")
        self.chk_autostart = builder.get_object("chk_autostart")

        #
        # spam filter tab
        #
        self.chk_enable_filter = builder.get_object("chk_enable_filter")
        self.textview_filter = builder.get_object("textview_filter")
        self.textbuffer_filter = builder.get_object("textbuffer_filter")

        #
        # events tab
        #
        self.chk_script0 = builder.get_object("chk_script0")
        self.filechooser_script0 = builder.get_object("filechooser_script0")
        self.chk_script1 = builder.get_object("chk_script1")
        self.filechooser_script1 = builder.get_object("filechooser_script1")

        #
        # about tab
        #
        self.image_logo = builder.get_object("image_logo")
        pb = GdkPixbuf.Pixbuf.new_from_file_at_size(get_data_file("mailnag.svg"), 200, 200)
        self.image_logo.set_from_pixbuf(pb)

        self.load_config()
        self.window.show()