"""$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/sendmail.py $
$Id: sendmail.py 22816 2003-10-22 23:23:34Z rmasse $

General interface for sending mail to users.
"""

from quixote.sendmail import sendmail as qx_sendmail
from quixote.sendmail import RFC822Mailbox
from dulcinea import local

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, force=False):
    """
    Wrapper for Quixote's sendmail() function.  Differences:
      * respects the local.SUPPRESS_EMAIL config setting
        except when the force keyword argument is true
      * always adds "Precedence", "X-No-Archive" headers
      * optionally adds "Reply-To" header
      * if smtp_sender not supplied, defaults to MAIL_SMTP_SENDER
        defined in local module rather than the addr-spec
        in from_addr

    See quixote.sendmail module for details (including argument types).
    """
    if not force and local.SUPPRESS_EMAIL:
        return

    # Control over the actual (SMTP) recipient of this message is now in
    # the hands of Quixote's sendmail(), guided by the mail_debug_addr
    # setting in the publisher's config.

    if extra_headers is None:
        extra_headers = []
    if (len(to_addrs) == 1 and
        type(to_addrs[0]) is str 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 running on kronos.
        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 = [RFC822Mailbox(args).format() for args in reply_to]
        extra_headers.append("Reply-To: %s" % ", ".join(reply_to))

    if smtp_sender is None:
        smtp_sender=local.MAIL_SMTP_SENDER
    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)

def format_email(user):
    """(user : DulcineaUser) -> (string, string)
    Return an e-mail, full name tuple that can be passed to
    our sendmail() function.
    """
    return user.get_email(), user.format_realname() or ''

