"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/sendmail.py $
$Id: sendmail.py 27873 2006-01-26 17:45:06Z dbinger $

General interface for sending mail to users.
"""
from dulcinea.common import is_qp, get_site_name, get_publisher
from dulcinea.site_util import is_email_enabled, is_live
from qp.mail.rfc822_mailbox import rfc822_mailbox
from quixote.sendmail import sendmail as qx_sendmail

def sendmail(subject, msg_body, to_addrs,
             from_addr=None, reply_to=None, smtp_sender=None,
             cc_addrs=None, extra_headers=None,
             smtp_recipients=None):
    """
    Wrapper for qx_sendmail() function.  Differences:
      * respects the site_util.is_email_enabled(), if it returns
        false then email is not sent
      * always adds "Precedence", "X-No-Archive" headers
      * optionally adds "Reply-To" header
      * if smtp_sender not supplied, defaults to the webmaster
        address from the publisher.
    """
    assert not is_qp()
    if not is_email_enabled():
        return

    # Control over the actual (SMTP) recipient of this message is now in
    # the hands of common_sendmail(), guided by the the site configuration.

    if extra_headers is None:
        extra_headers = []
    if (len(to_addrs) == 1 and
        isinstance(to_addrs[0], basestring) and
        to_addrs[0].startswith("webmaster@")):
        # Looks like this mail was generated by our feedback form.
        # Don't put in the "bulk mail" headers, because they suppress
        # the webmaster autoresponder.
        pass
    else:
        # Add these "bulk mail" headers for all other site-generated mail.
        # They're generally nice to put in auto-generated email.
        extra_headers.extend(["Precedence: junk", "X-No-Archive: yes"])

    if reply_to is not None:
        reply_to = [rfc822_mailbox(args).format() for args in reply_to]
        extra_headers.append("Reply-To: %s" % ", ".join(reply_to))

    if smtp_sender is None:
        smtp_sender = get_publisher().get_webmaster_address()

    if not is_live(get_site_name()):
        assert get_publisher().config.mail_debug_addr is not None
    qx_sendmail(subject, msg_body, to_addrs,
        from_addr=from_addr, extra_headers=extra_headers,
        cc_addrs=cc_addrs, smtp_sender=smtp_sender,
        smtp_recipients=smtp_recipients)



