import smtplib
import socket

from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.Header import Header

try:
    import docutils
    import docutils.core
except ImportError:
    docutils = None

from quixote import get_request

import errors
import misc

def email(subject, mail_body, email_rcpt, replyto = None, bcc = None,
        exclude_current_user = False):
    emails_cfg = misc.cfg.get('emails', {})

    mail_body = str(mail_body)
    try:
        htmlmail = docutils.core.publish_string(mail_body, writer_name="html",
                settings_overrides = {'input_encoding': 'iso-8859-15',
                    'output_encoding': 'iso-8859-15'})
    except:
        htmlmail = None

    msg = MIMEMultipart(_charset = 'iso-8859-15', _subtype = 'alternative')
    msg['Subject'] = Header(subject, 'iso-8859-15')
    if type(email_rcpt) is list:
        msg['To'] = ', '.join(email_rcpt)
    else:
        msg['To'] = email_rcpt
    msg['From'] = emails_cfg.get('from', 'noreply@entrouvert.com')
    if emails_cfg.get('reply_to'):
        msg['Reply-To'] = emails_cfg.get('reply_to')
    if replyto:
        msg['Reply-To'] = replyto

    msg.preamble = ''
    msg.epilogue = ''
    msg.attach(MIMEText(mail_body, _charset = 'iso-8859-15'))

    if htmlmail:
        msg.attach(MIMEText(htmlmail, _subtype = 'html', _charset = 'iso-8859-15'))

    if type(email_rcpt) is list:
        rcpts = email_rcpt[:]
    else:
        rcpts = [msg['To']]
    if bcc:
        rcpts += bcc

    if exclude_current_user:
        user = get_request().user
        if user and user.email and user.email in rcpts:
            rcpts.remove(user.email)

    try:
        s = smtplib.SMTP(emails_cfg.get('smtp_server', None) or 'localhost')
    except socket.error:
        # XXX: write message in a queue somewhere?
        raise errors.EmailError()
    if not s.sock:
        raise errors.EmailError()
    try:
        s.sendmail(emails_cfg.get('from', 'noreply@entrouvert.com'), rcpts, msg.as_string())
    except smtplib.SMTPRecipientsRefused:
        pass # XXX: log that.
    s.close()
