# Copyright (C) 1999 Milan Zamazal
#
# COPYRIGHT NOTICE
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.


"""Mailing.

This module provides the following functions:

 full_address -- fully qualify user address
 user -- user part of an e-mail address
 mail -- send mail
"""

__author__  = "Milan Zamazal <pdm@freesoft.cz>"
__version__ = "$Id: mail.py,v 1.8 1999/08/02 22:31:20 pdm Exp $"
__copyright__ = "GNU General Public License, version 2"


import mimify
import os
import socket
import string
import StringIO
import time

from gnats2w import config
from gnats2w.i18n import L


# Functions


def full_address (address):
    """If the e-mail 'address' does not contain '@', append host name to it.

    If it is not possible, return an empty string.

    If 'address' is an empty string, return it directly.
    """
    if not address:
        return address
    if string.find (address, '@') < 0:
        hostname, aliaslist, _ = \
          socket.gethostbyaddr (socket.gethostname ())
        if string.find (hostname, '.') < 0:
            for hostname in aliaslist:
                if string.find (hostname, '.') > 0:
                    break
            else:
                return ''
        address = address + '@' + hostname
    return address


def user (address):
    """Return user part of the 'address'.
    """
    address = string.split (address, '@')
    return address[0]


def mail (fr, to, cc, replyto, subject, message):
    """Send mail to given addresses.

    It does not bother about long headers.

    It tries to add coding header for the used language.

    Arguments:

     fr -- sender string
     to -- whom to send, string or sequence of strings
     cc -- whom to send copies, string or sequence of strings
     replyto -- what to set in reply-to
     subject -- subject
     message -- body of the mail

    Return result code of the mailer, or 'failed' if communication with the
    mailer fails.
    """
    # Prepare
    if type (to) != type (''):
        to = string.join (to, ',')
    if type (cc) != type (''):
        cc = string.join (cc, ',')
    if type (replyto) != type (''):
        replyto = string.join (replyto, ',')
    # Create complete message
    orig = StringIO.StringIO ()
    orig.write ('From: %s\n' % fr)
    orig.write ('To: %s\n' % to)
    if cc:
        orig.write ('Cc: %s\n' % cc)
    if replyto:
        orig.write ('Reply-To: %s\n' % replyto)
    orig.write ('Subject: %s\n' % subject)
    orig.write ('MIME-Version: 1.0\n')
    orig.write ('Content-Type: text/plain; charset=%s\n' % L.charset ())
    orig.write ('\n')
    orig.write (message)
    orig.write ('\n')
    orig.seek (0)
    # Send
    try:
        f = os.popen (config.MAIL, 'w')
        mimify_message (orig, f)
        return f.close ()
    except:
        return 'failed'


def mimify_message (instream, outstream):
    """Convert message to QP wrt. current language.

    Message, including headers, is available on 'instream' and will be written
    to 'outstream'.
    """
    mimify.CHARSET = L.charset ()
    mimify.mimify (instream, outstream)


def mimify_header_value (str):
    """Encode message header value wrt. current language and return the result.
    """
    mimify.CHARSET = L.charset ()
    str = str + '\n'
    str = mimify.mime_encode_header (str)
    return str[:-1]


def date ():
    """Return current date and time similar to the RFC 822 format.
    """
    t = time.gmtime (time.time ())
    return time.strftime ("%a, %d %b %Y %H:%M:%S +0000", t)
