aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatěj Cepl <mcepl@cepl.eu>2014-12-21 22:18:48 +0100
committerMatěj Cepl <mcepl@cepl.eu>2014-12-21 22:43:08 +0100
commit52b3df8247561fa138b273efd18e7f03a54880ef (patch)
treedb629d4d90eded920160dbf2c63b80e483fa8a4b
parentaaba562ae6e30c3b8e18938eea58f0a8df73bd57 (diff)
downloadpygn-52b3df8247561fa138b273efd18e7f03a54880ef.tar.gz
switch to argparse in pygn2m
and cleanup in pygn2m, news2mail.py (and some leftovers in pygm2n)
-rw-r--r--mail2news.py10
-rw-r--r--news2mail.py519
-rwxr-xr-xpygm2n3
-rwxr-xr-xpygn2m292
4 files changed, 378 insertions, 446 deletions
diff --git a/mail2news.py b/mail2news.py
index 3011a4e..e7cbcf9 100644
--- a/mail2news.py
+++ b/mail2news.py
@@ -14,11 +14,9 @@ Gets news email and sends it via SMTP.
class mail2news is hopefully conform to rfc850.
"""
-
import sys
from os import getpid
from socket import gethostbyaddr, gethostname
-import string
from re import findall
import nntplib
import pyginfo
@@ -79,14 +77,14 @@ class mail2news:
# if it is a multi-line header like Received:
if line[0] not in [' ', '\t']:
try:
- head, value = string.split(line, ' ', 1)
- except string.index_error:
+ head, value = line.split(' ', 1)
+ except ValueError:
value = ''
self.smtpheads[head] = value
else:
self.smtpheads[head] = '%s%s' % \
(self.smtpheads[head], line)
- except (string.index_error), message:
+ except (ValueError), message:
print('line: %s' % line)
print('(probably missing couple "Header: value" in %s)'
% line)
@@ -95,7 +93,7 @@ class mail2news:
elif len(line) > 0 and body:
self.body.append(line)
- except (string.index_error), message:
+ except (ValueError), message:
print message
sys.exit(1)
diff --git a/news2mail.py b/news2mail.py
index 73808b3..bfd6fd1 100644
--- a/news2mail.py
+++ b/news2mail.py
@@ -3,7 +3,7 @@
Author: Cosimo Alfarano
Date: June 11 2000
-news2mail.py - Copyright 2000 by Cosimo Alfarano <Alfarano@Students.CS.UniBo.It>
+news2mail.py - (C) 2000 by Cosimo Alfarano <Alfarano@Students.CS.UniBo.It>
You can use this software under the terms of the GPL. If we meet some day,
and you think this stuff is worth it, you can buy me a beer in return.
@@ -20,280 +20,271 @@ normal (what pygs does) operations flow is:
3) merges NNTP and SMTP heads into a unique heads
4) adds, renames and removes some heads
5) sorts remaining headers starting at top with Received: From: To: Subject:
- Date:, normal headers ending with X-* and Resent-* headers.
+ Date:, normal headers ending with X-* and Resent-* headers.
"""
-
import sys
import smtplib
-import string
-from re import compile
-#import getopt
import time
-#import rfc822
from socket import gethostbyaddr, gethostname
import tempfile
import pyginfo
+
class news2mail:
- """news to mail gateway class"""
-
- TMPFILE = tempfile.mktemp()
- wlfile = None
- logfile = None
-
- sender = ''
- rcpt = ''
- envelope = ''
-
- smtpserver = 'localhost'
-
- hostname = gethostbyaddr(gethostname())[0]
-
- heads_dict, smtpheads, nntpheads = {}, {}, {}
- article, headers, body = [], [], []
-
- debug = 1
-
- def readfile(self):
-
- for line in sys.stdin.readlines():
- self.article.append(line)
-
- if (len(self.article) == 1 and self.article[0][0] == '/'):
- file = self.article[0][:-1]
- del self.article[0]
- for line in open(file,'r').readlines():
- self.article.append(line)
-
-
- def parsearticle(self):
- """get news article from file or stdin and separate heads from body
-
- REMEBER: headers value has '\n' as last char.
- Use string[:-1] to ignore newline.
- """
-
- try:
- body = 0 # are we in body or in headers?
-
-# voidline = compile('^$') # I need '\n', ^$ matches anything
-# spaceending = compile('\s*\n$')
-
- for line in self.article:
- if not body and len(line) == 1:
- body = 1 # starts article body section
-
- if not body:
- try:
- head, value = string.split(line, ' ', 1)
- self.nntpheads[head] = value
- except (string.index_error), message:
- print 'string error: %s' % message
- print '(probably missing couple "Header: value" in %s)' % line
- sys.exit(1)
-
- elif len(line) > 0 and body:
- self.body.append(line)
-
- return self.nntpheads, self.body
-
-# except (re.error, string.index_error), message:
- except (string.index_error), message:
- print message
- sys.exit(1)
-
-
- def puthead(self, dict, list, key):
- """private, x-form dict entries in list entries"""
-
- if dict.has_key(key):
- list.append(key + ' ' + dict.get(key))
- else:
- return 0
- return 1
-
- def sortheads(self):
- """make list sorting heads, Received: From: To: Subject: first, others, X-*, Resent-* last"""
-
- set = ('Received:','From:','To:','Subject:','Date:') # put at top
-
- for k in set:
- self.puthead(self.heads_dict,self.headers,k)
-
- for k in self.heads_dict.keys():
- if k[:2] != 'X-' and k[:7] != 'Resent-' and k not in set:
- self.puthead(self.heads_dict,self.headers,k)
-
- for k in self.heads_dict.keys():
- if k[:2] == 'X-':
- self.puthead(self.heads_dict,self.headers,k)
-
- for k in self.heads_dict.keys():
- if k[:7] == 'Resent-':
- self.puthead(self.heads_dict,self.headers,k)
-
- return self.headers
-
-
- def mergeheads(self):
- """make a unique headers dictionary from NNTP and SMTP
- single headers dictionaries."""
-
- self.heads_dict = {}
-
-
- try:
- for header in self.nntpheads.keys(): # fill it w/ nntp old heads
- self.heads_dict[header] = self.nntpheads[header]
-
- for header in self.smtpheads.keys(): # and replace them w/ smtp new heads
- self.heads_dict[header] = self.smtpheads[header]
-
- except KeyError, message:
- print message
-
- return self.heads_dict
-
- def addheads(self):
- """add new header like X-Gateway: Received:
- """
-
- info = pyginfo.pygsinfo()
-
- try:
- self.heads_dict['X-Gateway:'] = info.PROGNAME + ' ' + \
- info.__doc__ + '\n'
-
- ##self.heads_dict['X-Gateway:'] = '%s %s\n' % (info.PROGNAME, info.__doc__)
-
- # to make Received: header
- t = time.ctime(time.time())
-
- if time.daylight:
- tzone = time.tzname[1]
- else:
- tzone = time.tzname[0]
-
- # An exemple from debian-italian:
- # Received: from murphy.debian.org (murphy.debian.org [216.234.231.6])
- # by smv04.iname.net (8.9.3/8.9.1SMV2) with SMTP id JAA26407
- # for <kame.primo@innocent.com> sent by
- # <debian-italian-request@lists.debian.org
-
- tmp = 'from GATEWAY by ' + self.hostname + \
- ' with ' + info.PROGNAME + \
- '\n\tfor <' + self.rcpt + '> ; ' + \
- t + ' (' + tzone +')\n'
-
- self.heads_dict['Received:'] = tmp
- except KeyError, message:
- print message
-
- return self.heads_dict
-
- def renameheads(self):
- """rename headers such as Newsgroups: to X-Newsgroups:
-
- headers renamed are useless or not rfc 822 copliant
- """
- try:
- if self.heads_dict.has_key('Newsgroups:'):
- self.heads_dict['X-Newsgroups:'] = self.heads_dict['Newsgroups:']
- del self.heads_dict['Newsgroups:']
-
- if self.heads_dict.has_key('NNTP-Posting-Host:'):
- self.heads_dict['X-NNTP-Posting-Host:'] = self.heads_dict['NNTP-Posting-Host:']
- del self.heads_dict['NNTP-Posting-Host:']
- except KeyError, message:
- print message
-
- return self.heads_dict
-
-
- def removeheads(self):
- """remove headers like Xref: Path: Lines:
- """
-
- try:
- # removing some others useless headers ....
-
- if self.heads_dict.has_key('Approved:'):
- del self.heads_dict['Approved:']
-
- if self.heads_dict.has_key('From'): # neither 'From ' nor 'From:'
- del self.heads_dict['From']
-
- if self.heads_dict.has_key('Xref:'):
- del self.heads_dict['Xref:']
-
- if self.heads_dict.has_key('Path:'):
- del self.heads_dict['Path:']
-
- if self.heads_dict.has_key('Lines:'):
- del self.heads_dict['Lines:']
-
- # it is usually set by INN, if ng is moderated...
- if self.heads_dict.has_key('Sender:'):
- del self.heads_dict['Sender:']
-
-
- if self.heads_dict.has_key('Message-id:'):
- self.heads_dict['Message-Id:'] = self.heads_dict['Message-id']
- del(self.heads_dict['Message-id'])
-
- if self.heads_dict.has_key('Message-ID:'):
- self.heads_dict['Message-Id:'] = self.heads_dict['Message-ID']
- del(self.heads_dict['Message-ID'])
-
- # If message-id is not present, I generate it
- if not self.heads_dict.has_key('Message-Id:'):
- # It should put a real user@domain
- msgid = 'pyg@puppapera.org'
-
- except KeyError, message:
- print message
-
- return self.heads_dict
-
- def sendarticle(self):
- """Talk to SMTP server and try to send email."""
- try:
- msglist = []
-
- s = smtplib.SMTP(self.smtpserver)
-
- # put real locahost domain name.
- s.helo(self.hostname)
- if s.helo_resp is None and s.ehlo_resp is None:
- print 'No helo resp'
- sys.exit(1)
-
- resp = s.mail(self.envelope)
- if resp[0] != 250:
- print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
- print 'envelope %s gave problem?' % self.envelope
- sys.exit(1)
- resp = s.rcpt(self.rcpt)
- if resp[0] != 250:
- print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
- sys.exit(1)
-
-
- msglist.append(string.join(self.headers,''))
-
- msglist.append(string.join(self.body,''))
- msg = string.join(msglist,'')
-
- s.data(msg)
- s.quit()
-
- return 1
-
- except (smtplib.SMTPException), messaggio:
- print messaggio
- sys.exit(1)
+ """news to mail gateway class"""
+
+ TMPFILE = tempfile.mktemp()
+ wlfile = None
+ logfile = None
+
+ sender = ''
+ rcpt = ''
+ envelope = ''
+
+ smtpserver = 'localhost'
+
+ hostname = gethostbyaddr(gethostname())[0]
+
+ heads_dict, smtpheads, nntpheads = {}, {}, {}
+ article, headers, body = [], [], []
+
+ debug = 1
+
+ def readfile(self):
+
+ for line in sys.stdin.readlines():
+ self.article.append(line)
+
+ if (len(self.article) == 1 and self.article[0][0] == '/'):
+ file = self.article[0][:-1]
+ del self.article[0]
+ for line in open(file, 'r').readlines():
+ self.article.append(line)
+
+ def parsearticle(self):
+ """get news article from file or stdin and separate heads from body
+
+ REMEBER: headers value has '\n' as last char.
+ Use string[:-1] to ignore newline.
+ """
+
+ try:
+ body = 0 # are we in body or in headers?
+
+# voidline = compile('^$') # I need '\n', ^$ matches anything
+# spaceending = compile('\s*\n$')
+
+ for line in self.article:
+ if not body and len(line) == 1:
+ body = 1 # starts article body section
+
+ if not body:
+ try:
+ head, value = line.split(' ', 1)
+ self.nntpheads[head] = value
+ except (ValueError), message:
+ print('string error: %s' % message)
+ print('(probably missing couple "Header: value" in %s)'
+ % line)
+ sys.exit(1)
+
+ elif len(line) > 0 and body:
+ self.body.append(line)
+
+ return self.nntpheads, self.body
+
+# except (re.error, ValueError), message:
+ except (ValueError), message:
+ print message
+ sys.exit(1)
+
+ def puthead(self, dict, list, key):
+ """private, x-form dict entries in list entries"""
+
+ if key in dict:
+ list.append(key + ' ' + dict.get(key))
+ else:
+ return 0
+ return 1
+
+ def sortheads(self):
+ """make list sorting heads, Received: From: To: Subject: first,
+ others, X-*, Resent-* last"""
+
+ set = ('Received:', 'From:', 'To:', 'Subject:', 'Date:') # put at top
+
+ for k in set:
+ self.puthead(self.heads_dict, self.headers, k)
+
+ for k in self.heads_dict.keys():
+ if k[:2] != 'X-' and k[:7] != 'Resent-' and k not in set:
+ self.puthead(self.heads_dict, self.headers, k)
+
+ for k in self.heads_dict.keys():
+ if k[:2] == 'X-':
+ self.puthead(self.heads_dict, self.headers, k)
+
+ for k in self.heads_dict.keys():
+ if k[:7] == 'Resent-':
+ self.puthead(self.heads_dict, self.headers, k)
+
+ return self.headers
+
+ def mergeheads(self):
+ """make a unique headers dictionary from NNTP and SMTP
+ single headers dictionaries."""
+
+ self.heads_dict = {}
+
+ try:
+ for header in self.nntpheads.keys(): # fill it w/ nntp old heads
+ self.heads_dict[header] = self.nntpheads[header]
+
+ # and replace them w/ smtp new heads
+ for header in self.smtpheads.keys():
+ self.heads_dict[header] = self.smtpheads[header]
+
+ except KeyError, message:
+ print message
+
+ return self.heads_dict
+
+ def addheads(self):
+ """add new header like X-Gateway: Received:
+ """
+
+ info = pyginfo.pygsinfo()
+
+ try:
+ self.heads_dict['X-Gateway:'] = info.PROGNAME + ' ' + \
+ info.__doc__ + '\n'
+
+ ##self.heads_dict['X-Gateway:'] = '%s %s\n' %
+ ## (info.PROGNAME, info.__doc__)
+
+ # to make Received: header
+ t = time.ctime(time.time())
+
+ if time.daylight:
+ tzone = time.tzname[1]
+ else:
+ tzone = time.tzname[0]
+
+ # An exemple from debian-italian:
+ # Received: from murphy.debian.org (murphy.debian.org [216.234.231.6])
+ # by smv04.iname.net (8.9.3/8.9.1SMV2) with SMTP id JAA26407
+ # for <kame.primo@innocent.com> sent by
+ # <debian-italian-request@lists.debian.org
+
+ tmp = 'from GATEWAY by ' + self.hostname + \
+ ' with ' + info.PROGNAME + \
+ '\n\tfor <' + self.rcpt + '> ; ' + \
+ t + ' (' + tzone + ')\n'
+
+ self.heads_dict['Received:'] = tmp
+ except KeyError, message:
+ print message
+
+ return self.heads_dict
+
+ def renameheads(self):
+ """rename headers such as Newsgroups: to X-Newsgroups:
+
+ headers renamed are useless or not rfc 822 copliant
+ """
+ try:
+ if 'Newsgroups:' in self.heads_dict:
+ self.heads_dict['X-Newsgroups:'] = \
+ self.heads_dict['Newsgroups:']
+ del self.heads_dict['Newsgroups:']
+
+ if 'NNTP-Posting-Host:' in self.heads_dict:
+ self.heads_dict['X-NNTP-Posting-Host:'] = \
+ self.heads_dict['NNTP-Posting-Host:']
+ del self.heads_dict['NNTP-Posting-Host:']
+ except KeyError, message:
+ print message
+
+ return self.heads_dict
+
+ def removeheads(self):
+ """remove headers like Xref: Path: Lines:
+ """
+
+ try:
+ # removing some others useless headers ....
+
+ if 'Approved:' in self.heads_dict:
+ del self.heads_dict['Approved:']
+
+ if 'From' in self.heads_dict: # neither 'From ' nor 'From:'
+ del self.heads_dict['From']
+
+ if 'Xref:' in self.heads_dict:
+ del self.heads_dict['Xref:']
+
+ if 'Path:' in self.heads_dict:
+ del self.heads_dict['Path:']
+
+ if 'Lines:' in self.heads_dict:
+ del self.heads_dict['Lines:']
+
+ # it is usually set by INN, if ng is moderated...
+ if 'Sender:' in self.heads_dict:
+ del self.heads_dict['Sender:']
+
+ if 'Message-id:' in self.heads_dict:
+ self.heads_dict['Message-Id:'] = self.heads_dict['Message-id']
+ del(self.heads_dict['Message-id'])
+
+ if 'Message-ID:' in self.heads_dict:
+ self.heads_dict['Message-Id:'] = self.heads_dict['Message-ID']
+ del(self.heads_dict['Message-ID'])
+
+ # If message-id is not present, I generate it
+ if 'Message-Id:' not in self.heads_dict:
+ # It should put a real user@domain
+ msgid = 'pyg@puppapera.org' # FIXME unused variable
+
+ except KeyError, message:
+ print message
+
+ return self.heads_dict
+
+ def sendarticle(self):
+ """Talk to SMTP server and try to send email."""
+ try:
+ msglist = []
+
+ s = smtplib.SMTP(self.smtpserver)
+
+ # put real locahost domain name.
+ s.helo(self.hostname)
+ if s.helo_resp is None and s.ehlo_resp is None:
+ print 'No helo resp'
+ sys.exit(1)
+
+ resp = s.mail(self.envelope)
+ if resp[0] != 250:
+ print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
+ print 'envelope %s gave problem?' % self.envelope
+ sys.exit(1)
+ resp = s.rcpt(self.rcpt)
+ if resp[0] != 250:
+ print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
+ sys.exit(1)
+
+ msglist.append(''.join(self.headers))
+ msglist.append(''.join(self.body))
+ msg = ''.join(msglist)
+ s.data(msg)
+ s.quit()
+ return 1
+ except (smtplib.SMTPException), messaggio:
+ print messaggio
+ sys.exit(1)
diff --git a/pygm2n b/pygm2n
index ba98908..49d83c3 100755
--- a/pygm2n
+++ b/pygm2n
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""News to mail gateway script. Copyright 2000 Cosimo Alfarano
Author: Cosimo Alfarano
@@ -63,8 +64,6 @@ def parse_cmdline():
if not args.newsgroup:
raise argparse.ArgumentError('Error: Missing Newsgroups\n')
- logging.debug('args = %s', args)
-
return args
diff --git a/pygn2m b/pygn2m
index d093756..0b958f1 100755
--- a/pygn2m
+++ b/pygn2m
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-
+# -*- coding: utf-8 -*-
"""News to mail gateway script. Copyright 2000 Cosimo Alfarano
Author: Cosimo Alfarano
@@ -13,202 +13,146 @@ Thanks to md for this useful formula. Beer is beer.
Gets news article from stdin and sends it via SMTP.
"""
-
-import sys, os
-import getopt
-from string import split
+from __future__ import print_function
+import sys
+import os
+import argparse
sys.path.append('/usr/lib/pyg')
import pyginfo
import whitelist
import news2mail
-#import mail2news
-
-
-def parse_cmdline(gw):
- """Parses cmdline with getopt.
- set a dictionary with smtp new header in gw parameter (gw.smtpheads)
- return (test,verbose) boolean tuple
- """
-
- opt, arg = None, None
- test, verbose = 0, 0
- retnull = (None, None)
-
- try:
- opt, arg = getopt.getopt(sys.argv[1:],"H:t:s:e:w:l:hdvVT")
- except (getopt.error), message:
- print '%s: %s\n' % (sys.argv[0], message)
- sys.exit(1)
-
- if len(sys.argv) == 1 or opt == []:
- gw.smtpheads = None
- return retnull
-
- for i in range(len(opt)):
- if opt[i][0] == '-h':
- gw.smtpheads = None
- return retnull
- elif opt[i][0] == '-v':
- gw.smtpheads = None
- return retnull
- elif opt[i][0] == '-H':
- gw.smtpserver = opt[i][1]
- elif opt[i][0] == '-s':
- gw.smtpheads['Resent-Sender:'] = opt[i][1] + '\n'
- gw.sender = opt[i][1]
- elif opt[i][0] == '-t' or opt[i][0] == '-r':
- gw.smtpheads['To:'] = opt[i][1] + '\n'
- gw.rcpt = opt[i][1]
- elif opt[i][0] == '-e':
- gw.smtpheads['Resent-From:'] = opt[i][1] + '\n' #envelope
- gw.envelope = opt[i][1]
- elif opt[i][0] == '-w':
- gw.wlfile = opt[i][1]
- elif opt[i][0] == '-l':
- gw.logfile = opt[i][1]
- elif opt[i][0] == '-d':
- gw.debug = 1
- elif opt[i][0] == '-T':
- test = 1
- elif opt[i][0] == '-V':
- verbose = 1
-
-# By rfc822 [Resent-]Sender: should be ever set, unless == From:
+
+
+def parse_cmdline():
+ """
+ set a dictionary with smtp new header in gw parameter (gw.smtpheads)
+ return (test,verbose) boolean tuple
+ """
+ i = pyginfo.pygsinfo()
+ parser = argparse.ArgumentParser(
+ description='%s version %s - Copyright 2000 Cosimo Alfarano\n%s' %
+ (i.PROGNAME, i.VERSION, i.__doc__))
+
+ parser.add_argument('-H', '--smtpserver', default='')
+ parser.add_argument('-s', '--sender', required=True, default='')
+ parser.add_argument('-e', '--envelope', default='')
+ parser.add_argument('-t', '--to', dest='rcpt', required=True)
+ parser.add_argument('-w', '--wlfile')
+ parser.add_argument('-l', '--logfile')
+
+ # TODO eventually we should refactor these to be Boolean
+ # and use store_true
+ parser.add_argument('-T', '--test',
+ help='test mode (not send article via SMTP)',
+ action='store_true')
+ parser.add_argument('-d', '--debug',
+ action='store_true')
+ parser.add_argument('-V', '--verbose', help='verbose output',
+ action='store_true')
+
+ opts = parser.parse_args()
+
+# By rfc822 [Resent-]Sender: should be ever set, unless == From:
# (not this case). Should be a human, while [Resent-]From: may be a program.
- if gw.rcpt == '' or gw.sender == '':
- print 'missing command line option'
- gw.smtpheads = None
- return retnull
+ if opts.rcpt == '' or opts.sender == '':
+ raise argparse.ArgumentError('missing command line option')
- if gw.envelope == '' and gw.sender != '':
- gw.smtpheads['Resent-From:'] = gw.sender + '\n'
- gw.envelope = gw.sender
- elif gw.envelope == -1:
- gw.smtpheads = None
- return retnull
+ if opts.envelope == '' and opts.sender != '':
+ opts.envelope = opts.sender
- sys.argv[1:] = arg
+ return opts
- return (test, verbose)
+"""main is structured in 4 phases:
+ 1) check and set pyg's internal variables
+ 2) check whitelist for users' permission
+ 3) format rfc 822 headers from input article
+ 4) open smtp connection and send e-mail
+"""
-def usage():
- i = pyginfo.pygsinfo()
+try:
- print '%s version %s - Copyright 2000 Cosimo Alfarano' % (i.PROGNAME, i.VERSION)
- print i.__doc__
- print
- print 'usage: %s [-h] [-d] [-T] [-V] [-H smtphost] [-l logfile] [-w whitelist] -t recipient@... -s sender@... [-e envelope@...]' % split(sys.argv[0],'/')[-1]
- print '-t -s recipient, sender are necessary'
- print '-e envelope [default: same of sender]'
- print '-T for test mode (not send article via SMTP)'
- print '-V for verbose output'
- print '-d for debug'
- print '-h or -v for this info'
-
+ """phase 1:
+ check and set pyg's internal variables
+ """
+ n2m = news2mail.news2mail()
+ owner = None
+ # it returns only test, other parms are set directly in the actual
+ # parameter
+ args = parse_cmdline()
+ # check if n2m has some file prefercences set on commandline
+ if n2m.wlfile is None:
+ wl = os.environ['HOME'] + '/pyg.whitelist'
+ else:
+ wl = n2m.wlfile
+ if n2m.logfile is None:
+ log = os.environ['HOME'] + '/pyg.log'
+ else:
+ log = n2m.logfile
+# print 'using %s %s\n' % (wl,log)
+ wl = whitelist.whitelist(wl, log)
-"""main is structured in 4 phases:
- 1) check and set pyg's internal variables
- 2) check whitelist for users' permission
- 3) format rfc 822 headers from input article
- 4) open smtp connection and send e-mail
-"""
+ # reads stdin and parses article separating head from body
+ n2m.readfile()
+ n2m.parsearticle()
+ """phase 2:
+ check whitelist for user's permission
+ """
-try:
+ # make a first check of From: address
+ owner = wl.checkfrom(n2m.nntpheads['From:'])
+ if owner is None:
+ if sys.stdin.isatty() == 1 or args.test:
+ print ('"%s" is not in whitelist!' % (n2m.nntpheads['From:'][:-1]))
+ else:
+ wl.logmsg(n2m.nntpheads, wl.DENY)
+
+ # if verbose, I want to print out headers, so I can't
+ # exit now.
+ if not args.verbose:
+ sys.exit(1)
+
+ """phase 3:
+ format rfc 822 headers from input article
+ """
+
+ n2m.mergeheads() # make unique dict from NNTP and SMTP dicts
+
+ n2m.addheads() # add some important heads
+ n2m.renameheads() # rename useless heads
+ n2m.removeheads() # remove other heads
+
+ n2m.sortheads() # sort remaining heads :)
+
+ # prints formatted email message only (without send) if user wants
+ if args.verbose:
+ for line in n2m.headers:
+ print(line[:-1])
+
+ if args.owner is None:
+ sys.exit(1)
+
+ """phase 4:
+ open smtp connection and send e-mail
+ """
- """phase 1:
- check and set pyg's internal variables
- """
-
- n2m = news2mail.news2mail()
- owner = None
-
- # it returns only test, other parms are set directly in the actual parameter
- (test, verbose) = parse_cmdline(n2m)
- if (test, verbose) == (None, None):
- usage()
- sys.exit(0)
-
-
- # check if n2m has some file prefercences set on commandline
- if(n2m.wlfile == None):
- wl = os.environ['HOME'] + '/pyg.whitelist'
- else:
- wl = n2m.wlfile
-
- if(n2m.logfile == None):
- log = os.environ['HOME'] + '/pyg.log'
- else:
- log = n2m.logfile
-
-# print 'using %s %s\n' % (wl,log)
-
- wl = whitelist.whitelist(wl,log)
-
- # reads stdin and parses article separating head from body
- n2m.readfile()
- n2m.parsearticle()
-
-
- """phase 2:
- check whitelist for user's permission
- """
-
- # make a first check of From: address
- owner = wl.checkfrom(n2m.nntpheads['From:'])
- if(owner == None):
- if(sys.stdin.isatty()==1 or test):
- print ('"%s" is not in whitelist!' % (n2m.nntpheads['From:'][:-1]))
- else:
- wl.logmsg(n2m.nntpheads,wl.DENY)
-
- # if verbose, I want to print out headers, so I can't
- # exit now.
- if(not verbose):
- sys.exit(1)
-
- """phase 3:
- format rfc 822 headers from input article
- """
-
- n2m.mergeheads() # make unique dict from NNTP and SMTP dicts
-
- n2m.addheads() # add some important heads
- n2m.renameheads() # rename useless heads
- n2m.removeheads() # remove other heads
-
- n2m.sortheads() # sort remaining heads :)
-
- # prints formatted email message only (without send) if user wants
- if(verbose):
- for line in n2m.headers:
- print line[:-1]
-
- if(owner == None):
- sys.exit(1)
-
-
- """phase 4:
- open smtp connection and send e-mail
- """
-
- if len(n2m.headers) > 0:
- wl.logmsg(n2m.heads_dict,wl.ACCEPT,owner)
- if(not test):
- n2m.sendarticle()
- else:
- print 'Error: No Headers!!!'
+ if len(n2m.headers) > 0:
+ wl.logmsg(n2m.heads_dict, wl.ACCEPT, owner)
+ if not args.test:
+ n2m.sendarticle()
+ else:
+ print('Error: No Headers!!!')
except KeyboardInterrupt:
- print 'Keyboard Interrupt'
- sys.exit(1)
+ print('Keyboard Interrupt')
+ sys.exit(1)