# $Id: sendmail.py,v 1.11 2001/10/15 18:19:49 kjetilja Exp $

## System modules
from gtk import *
from gnome.ui import *

## Error messages from the GUI
err1 = """Unable to connect to mail server"""
err2 = """Unable to send mail to the specified recipient(s)"""
err3 = """Sendmail command did not succeed in sending the mail"""
err4 = """Sendmail returned the following:\n\n%s"""

## Warning messages from the GUI
warn1 = """Unable to perform clean SMTP disconnect for server:\n%s"""


## Send mail by explicit connect to mail server
def sendmail_server(host, frm, to, msg):
    # Connect to outgoing mail host
    import smtplib
    try:
        smail = smtplib.SMTP(host)
    except:
        w = GnomeErrorDialog(err1)
        w.show()
        return 0

    # Blast message to server (handle the CC and TO recipients)
    try:
        smail.sendmail(frm, to, msg)
    except:
        try:
            smail.quit()
        except:
            pass
        w = GnomeErrorDialog(err2)
        w.show()
        return 0
    
    try:
        # We might get a premature disconnect even though the message
        # got through ok.  Print a warning to alert the user since I'm
        # not convinced the mail got through.
        smail.quit()
    except:
        w = GnomeWarningDialog(warn1 % host)
        w.show()
    return 1


## Use local sendmail command to send mail
def sendmail_cmd(cmd, msg):
    import popen2
    try: 
        r,w,e = popen2.popen3("%s -t -i" % cmd, 8192)
    except:
        w = GnomeErrorDialog(err3) 
        w.show() 
        return 0 
    w.write(msg + "\n\n")
    w.close()
    try:
        errors = r.read()
    except IOError:
	errors = ''
    r.close()
    e.close()
    if errors != '':
        w = GnomeErrorDialog(err4 % errors)
        w.show()
        return 0
    return 1
