aboutsummaryrefslogblamecommitdiffstats
path: root/mail2news.py
blob: 88c53ea50d225e1c8f9e8cfaa1ac0448b5a4dd61 (plain) (tree)
1
2
3
4
5
6




                                                              
                                                                          









                                                                          
                                   

              
              
                     
                      


                                             






                                                               
 



                                    











                                                                             
                  
 
                            
 
                                                         
 





                                                                
 

                               
                                                        
                              
                                                     

                
 
                 
                                          

                                                           




                                                            
 
                         
                                                              
                                       
 

                                                   









                                                               

                                              



                                                                      

                                            
                                                                              


                                                          



                                                             
                                                  
                                                             


                                                                   
                                                                   
 




                                 
                                      





                                                                           

                                                                         

                                     
 
                                
                                           
                                             
 
                                                   













                                                                           





                                 





























                                                                         


                                                        

                                                                   




                                        
 

                                     

                               






















                                              


                                                                            
"""Mail to news gateway script. Copyright 2000 Cosimo Alfarano

Author: Cosimo Alfarano
Date: September 16 2000

mail2news.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.

Thanks to md for this useful formula. Beer is beer.

Gets news email and sends it via SMTP.

class mail2news is  hopefully conform to rfc850.

"""
from collections import OrderedDict
import email
import logging
import nntplib
from os import getpid
from re import findall
from socket import gethostbyaddr, gethostname
import sys


#logging.basicConfig(level=logging.DEBUG)
# This is the single source of Truth
# Yes, it is awkward to have it assymetrically here
# and not in news2mail as well.
VERSION = '0.9.9'
DESC = "The Python Gateway Script: news2mail mail2news gateway"


class mail2news:
    """news to mail gateway class"""

    reader = None                # mode reader
#    newsgroups = None            # Newsgroups: local.test,local.moderated...
#    approved = None                # Approved: kame@aragorn.lorien.org
    newsserver = 'localhost'    # no comment :)
    port = 119
    user = None
    password = None

    hostname = gethostbyaddr(gethostname())[0]

    heads_dict, smtpheads, nntpheads = {}, {}, {}
    email, headers, body = [], [], []
    message = None

    def readfile(self, opt):

        self.message = email.message_from_file(sys.stdin)

        if (len(self.message) == 0) \
                and self.message.get_payload().startswith('/'):
            msg_file_name = self.message.get_payload().strip()
            del self.message
            with open(msg_file_name, 'r') as msg_file:
                self.message = email.message_from_file(msg_file)

        # introduce nntpheads
        if opt.newsgroup != '':
            self.nntpheads['Newsgroups'] = opt.newsgroup
        if opt.approver != '':
            self.nntpheads['Approved'] = opt.approver

        return 1

    @staticmethod
    def puthead(from_dict, out_list, key):
        """private, x-form dict entries in out_list entries
        """
        if key in from_dict:
            out_list.append(key + ': ' + from_dict.get(key))
        else:
            return 0
        return 1

    def mergeheads(self):
        """make a unique headers dictionary from NNTP and SMTP
        single headers dictionaries."""

        self.heads_dict = OrderedDict(self.message)
        self.heads_dict.update(self.nntpheads)
        return self.heads_dict

    def renameheads(self):
        """rename headers such as Resent-*: to X-Resent-*:

        headers renamed are useless or not rfc 977/850 copliant
        handles References/In-Reply-To headers
        """
        try:

            for key in self.heads_dict.keys():
                if(key[:7] in ['Resent-']):
                    if ('X-' + key) in self.heads_dict:
                        self.heads_dict['X-Original-' + key] = \
                            self.heads_dict['X-' + key]
                    self.heads_dict['X-' + key] = self.heads_dict[key]
                    del self.heads_dict[key]

            # In rfc822 References: is considered, but many MUA doen't put it.
            if ('References' not in self.heads_dict) and \
                    ('In-Reply-To' in self.heads_dict):
                print self.heads_dict['In-Reply-To']

                # some MUA uses msgid without '<' '>'
#                ref = findall('([^\s<>\']+@[^\s<>;:\']+)', \
                # but I prefer use RFC standards
                ref = findall('(<[^<>]+@[^<>]+>)',
                              self.heads_dict['In-Reply-To'])

                # if found, keep first element that seems a Msg-ID.
                if(ref and len(ref)):
                    self.heads_dict['References'] = '%s\n' % ref[0]

        except KeyError, message:
            print message

        return self.heads_dict

    def removeheads(self, heads=None):
        """remove headers like Xref: Path: Lines:
        """

        try:
            # removing some others useless headers .... (From is not From:)

            rmheads = ['Received', 'From ', 'NNTP-Posting-Host',
                       'X-Trace', 'X-Compliants-To', 'NNTP-Posting-Date']
            if(heads):
                rmheads.append(heads)

            for head in rmheads:
                if head in self.heads_dict:
                    del self.heads_dict[head]

            if 'Message-Id' not in self.heads_dict:
                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:
                    msgid = '<pyg.%d@tuchailepuppapera.org>\n' % (getpid())
                    self.heads_dict['Message-Id'] = msgid

        except KeyError, message:
            print message

        return self.heads_dict

    def sortheads(self):
        """make list sorted by heads: From: To: Subject: first,
           others, X-*, X-Resent-* last"""

        # put at top
        head_set = ('Newsgroups', 'From', 'To', 'X-To', 'Cc', 'Subject',
                    'Date', 'Approved', 'References', 'Message-Id')

        logging.debug('self.heads_dict = %s', self.heads_dict)

        for k in head_set:
            self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if not k.startswith('X-') and not k.startswith('X-Resent-') \
                    and k not in head_set:
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k.startswith('X-'):
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k.startswith('X-Resent-'):
                self.puthead(self.heads_dict, self.headers, k)

        logging.debug('self.headers = %s', self.headers)

        return self.headers

    def sendemail(self):
        """Talk to NNTP server and try to send email."""
        try:
            n = nntplib.NNTP(self.newsserver, self.port, self.user,
                             self.password)

            if(self.reader):
                n.putline('mode reader')
                resp = n.getline()
                print resp

            resp = n.shortcmd('POST')

            # sett RFC977 2.4.2
            if resp[0] != '3':
                raise n.error_reply, str(resp)

            for line in self.headers:
                if not line:
                    break
                if line[-1] == '\n':
                    line = line[:-1]
                if line[:1] == '.':
                    line = '.' + line
                n.putline(line)

            for line in self.body:
                if not line:
                    break
                if line[-1] == '\n':
                    line = line[:-1]
                if line[:1] == '.':
                    line = '.' + line
                n.putline(line)

            n.putline('.')
            n.quit()
            return None
        except (nntplib.error_reply, nntplib.error_temp, nntplib.error_perm,
                nntplib.error_proto, nntplib.error_data), message:
            return 'NNTP: ' + str(message)