Пример #1
0
def send_with_template(prefix, parm, test=None):
    """ Send an email using template """

    parm['from'] = cfg.email_from()
    parm['date'] = get_email_date()

    lst = []
    path = cfg.email_dir.get_path()
    if path and os.path.exists(path):
        try:
            lst = glob.glob(os.path.join(path, '%s-*.tmpl' % prefix))
        except:
            logging.error(Ta('Cannot find email templates in %s'), path)
    else:
        path = os.path.join(sabnzbd.DIR_PROG, DEF_EMAIL_TMPL)
        tpath = os.path.join(path, '%s-%s.tmpl' % (prefix, cfg.language()))
        if os.path.exists(tpath):
            lst = [tpath]
        else:
            lst = [os.path.join(path, '%s-en.tmpl' % prefix)]

    sent = False
    for temp in lst:
        if os.access(temp, os.R_OK):
            source = _decode_file(temp)
            if source:
                sent = True
                if test:
                    recipients = [test.get('email_to')]
                else:
                    recipients = cfg.email_to()

                if len(recipients):
                    for recipient in recipients:
                        parm['to'] = recipient
                        message = Template(source=source,
                                           searchList=[parm],
                                           filter=EmailFilter,
                                           compilerSettings={
                                               'directiveStartToken': '<!--#',
                                               'directiveEndToken': '#-->'
                                           })
                        ret = send(message.respond(), recipient, test)
                        del message
                else:
                    ret = T('No recipients given, no email sent')
            else:
                ret = T('Invalid encoding of email template %s') % temp
                errormsg(ret)
    if not sent:
        ret = T('No email templates found')
        errormsg(ret)
    return ret
Пример #2
0
def send_with_template(prefix, parm, test=None):
    """ Send an email using template """

    parm['from'] = cfg.email_from()
    parm['date'] = get_email_date()

    lst = []
    path = cfg.email_dir.get_path()
    if path and os.path.exists(path):
        try:
            lst = glob.glob(os.path.join(path, '%s-*.tmpl' % prefix))
        except:
            logging.error(Ta('Cannot find email templates in %s'), path)
    else:
        path = os.path.join(sabnzbd.DIR_PROG, DEF_EMAIL_TMPL)
        tpath = os.path.join(path, '%s-%s.tmpl' % (prefix, cfg.language()))
        if os.path.exists(tpath):
            lst = [tpath]
        else:
            lst = [os.path.join(path, '%s-en.tmpl' % prefix)]

    sent = False
    for temp in lst:
        if os.access(temp, os.R_OK):
            source = _decode_file(temp)
            if source:
                sent = True
                if test:
                    recipients = [ test.get('email_to') ]
                else:
                    recipients = cfg.email_to()

                if len(recipients):
                    for recipient in recipients:
                        parm['to'] = recipient
                        message = Template(source=source,
                                            searchList=[parm],
                                            filter=EmailFilter,
                                            compilerSettings={'directiveStartToken': '<!--#',
                                                              'directiveEndToken': '#-->'})
                        ret = send(message.respond(), recipient, test)
                        del message
                else:
                    ret = T('No recipients given, no email sent')
            else:
                ret = T('Invalid encoding of email template %s') % temp
                errormsg(ret)
    if not sent:
        ret = T('No email templates found')
        errormsg(ret)
    return ret
Пример #3
0
def send_with_template(prefix, parm, test=None):
    """ Send an email using template """
    parm["from"] = cfg.email_from()
    parm["date"] = get_email_date()

    ret = None
    email_templates = []
    path = cfg.email_dir.get_path()
    if path and os.path.exists(path):
        try:
            email_templates = glob.glob(
                os.path.join(path, "%s-*.tmpl" % prefix))
        except:
            logging.error(T("Cannot find email templates in %s"), path)
    else:
        path = os.path.join(sabnzbd.DIR_PROG, DEF_EMAIL_TMPL)
        tpath = os.path.join(path, "%s-%s.tmpl" % (prefix, cfg.language()))
        if os.path.exists(tpath):
            email_templates = [tpath]
        else:
            email_templates = [os.path.join(path, "%s-en.tmpl" % prefix)]

    for template_file in email_templates:
        logging.debug("Trying to send email using template %s", template_file)
        if os.access(template_file, os.R_OK):
            if test:
                recipients = [test.get("email_to")]
            else:
                recipients = cfg.email_to()

            if len(recipients):
                for recipient in recipients:
                    # Force-open as UTF-8, otherwise Cheetah breaks it
                    with open(template_file, "r",
                              encoding="utf-8") as template_fp:
                        parm["to"] = recipient
                        message = Template(file=template_fp,
                                           searchList=[parm],
                                           compilerSettings=CHEETAH_DIRECTIVES)
                        ret = send_email(message.respond(), recipient, test)
            else:
                ret = T("No recipients given, no email sent")
        else:
            # Can't open or read file, stop
            return errormsg(T("Cannot read %s") % template_file)

    # Did we send any emails at all?
    if not ret:
        ret = T("No email templates found")
    return ret
Пример #4
0
def diskfull():
    """ Send email about disk full, no templates """

    if cfg.email_full():
        return send(T('''To: %s
From: %s
Date: %s
Subject: SABnzbd reports Disk Full

Hi,

SABnzbd has stopped downloading, because the disk is almost full.
Please make room and resume SABnzbd manually.

''') % (cfg.email_to.get_string(), cfg.email_from(), get_email_date()), cfg.email_to())
    else:
        return ""
Пример #5
0
def diskfull():
    """ Send email about disk full, no templates """

    if cfg.email_full():
        return send(T('''To: %s
From: %s
Date: %s
Subject: SABnzbd reports Disk Full

Hi,

SABnzbd has stopped downloading, because the disk is almost full.
Please make room and resume SABnzbd manually.

''') % (cfg.email_to.get_string(), cfg.email_from(), get_email_date()), cfg.email_to())
    else:
        return ""
Пример #6
0
def send_email(message, email_to, test=None):
    """ Send message if message non-empty and email-parms are set """
    # we should not use CFG if we are testing. we should use values
    # from UI instead.
    # email_to is replaced at send_with_template, since it can be an array
    if test:
        email_server = test.get("email_server")
        email_from = test.get("email_from")
        email_account = test.get("email_account")
        email_pwd = test.get("email_pwd")
        if email_pwd and not email_pwd.replace("*", ""):
            # If all stars, get stored password instead
            email_pwd = cfg.email_pwd()
    else:
        email_server = cfg.email_server()
        email_from = cfg.email_from()
        email_account = cfg.email_account()
        email_pwd = cfg.email_pwd()

    if not message.strip("\n\r\t "):
        return "Skipped empty message"

    # Prepare the email
    email_message = _prepare_message(message)

    if email_server and email_to and email_from:
        server, port = split_host(email_server)
        if not port:
            port = 25
        logging.debug("Connecting to server %s:%s", server, port)

        try:
            mailconn = smtplib.SMTP_SSL(server, port)
            mailconn.ehlo()
            logging.debug("Connected to server %s:%s", server, port)
        except:
            # Non SSL mail server
            logging.debug("Non-SSL mail server detected reconnecting to server %s:%s", server, port)

            try:
                mailconn = smtplib.SMTP(server, port)
                mailconn.ehlo()
            except:
                logging.info("Traceback: ", exc_info=True)
                return errormsg(T("Failed to connect to mail server"))

        # TLS support
        if mailconn.ehlo_resp:
            m = re.search(b"STARTTLS", mailconn.ehlo_resp, re.IGNORECASE)
            if m:
                logging.debug("TLS mail server detected")
                try:
                    mailconn.starttls()
                    mailconn.ehlo()
                except:
                    logging.info("Traceback: ", exc_info=True)
                    return errormsg(T("Failed to initiate TLS connection"))

        # Authentication
        if (email_account != "") and (email_pwd != ""):
            try:
                mailconn.login(email_account, email_pwd)
            except smtplib.SMTPHeloError:
                return errormsg(T("The server didn't reply properly to the helo greeting"))
            except smtplib.SMTPAuthenticationError:
                return errormsg(T("Failed to authenticate to mail server"))
            except smtplib.SMTPException:
                return errormsg(T("No suitable authentication method was found"))
            except:
                logging.info("Traceback: ", exc_info=True)
                return errormsg(T("Unknown authentication failure in mail server"))

        try:
            mailconn.sendmail(email_from, email_to, email_message)
            msg = None
        except smtplib.SMTPHeloError:
            msg = errormsg("The server didn't reply properly to the helo greeting.")
        except smtplib.SMTPRecipientsRefused:
            msg = errormsg("The server rejected ALL recipients (no mail was sent).")
        except smtplib.SMTPSenderRefused:
            msg = errormsg("The server didn't accept the from_addr.")
        except smtplib.SMTPDataError:
            msg = errormsg("The server replied with an unexpected error code (other than a refusal of a recipient).")
        except:
            logging.info("Traceback: ", exc_info=True)
            msg = errormsg(T("Failed to send e-mail"))

        try:
            mailconn.close()
        except:
            logging.info("Traceback: ", exc_info=True)
            errormsg(T("Failed to close mail connection"))

        if msg:
            return msg
        else:
            logging.info("Notification e-mail successfully sent")
            return T("Email succeeded")
    else:
        return T("Cannot send, missing required data")
Пример #7
0
def send(message, email_to, test=None):
    """ Send message if message non-empty and email-parms are set """

    # we should not use CFG if we are testing. we should use values
    # from UI instead.

    if test:
        email_server  = test.get('email_server')
        email_from    = test.get('email_from')
        email_account = test.get('email_account')
        email_pwd     = test.get('email_pwd')
        if email_pwd and not email_pwd.replace('*', ''):
            # If all stars, get stored password instead
            email_pwd = cfg.email_pwd()
    else:
        email_server  = cfg.email_server()
        email_from    = cfg.email_from()
        email_account = cfg.email_account()
        email_pwd     = cfg.email_pwd()

    # email_to is replaced at send_with_template, since it can be an array

    if not message.strip('\n\r\t '):
        return "Skipped empty message"

    if email_server and email_to and email_from:

        message = _prepare_message(message)

        server, port = split_host(email_server)
        if not port:
            port = 25

        logging.debug("Connecting to server %s:%s", server, port)

        try:
            mailconn = ssmtplib.SMTP_SSL(server, port)
            mailconn.ehlo()

            logging.debug("Connected to server %s:%s", server, port)

        except Exception, errorcode:
            if errorcode[0]:

                # Non SSL mail server
                logging.debug("Non-SSL mail server detected " \
                             "reconnecting to server %s:%s", server, port)

                try:
                    mailconn = smtplib.SMTP(server, port)
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to connect to mail server'))
            else:
                return errormsg(T('Failed to connect to mail server'))

        # TLS support
        if mailconn.ehlo_resp:
            m = re.search('STARTTLS', mailconn.ehlo_resp, re.IGNORECASE)
            if m:
                logging.debug("TLS mail server detected")

                try:
                    mailconn.starttls()
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to initiate TLS connection'))

        # Authentication
        if (email_account != "") and (email_pwd != ""):
            try:
                mailconn.login(email_account, email_pwd)
            except smtplib.SMTPHeloError:
                return errormsg(T("The server didn't reply properly to the helo greeting"))
            except smtplib.SMTPAuthenticationError:
                return errormsg(T("Failed to authenticate to mail server"))
            except smtplib.SMTPException:
                return errormsg(T("No suitable authentication method was found"))
            except:
                return errormsg(T("Unknown authentication failure in mail server"))

        try:
            mailconn.sendmail(email_from, email_to, message)
            msg = None
        except smtplib.SMTPHeloError:
            msg = errormsg('The server didn\'t reply properly to the helo greeting.')
        except smtplib.SMTPRecipientsRefused:
            msg = errormsg('The server rejected ALL recipients (no mail was sent).')
        except smtplib.SMTPSenderRefused:
            msg = errormsg('The server didn\'t accept the from_addr.')
        except smtplib.SMTPDataError:
            msg = errormsg('The server replied with an unexpected error code (other than a refusal of a recipient).')
        except:
            msg = errormsg(T('Failed to send e-mail'))

        try:
            mailconn.close()
        except:
            errormsg(T('Failed to close mail connection'))

        if msg:
            return msg
        else:
            logging.info("Notification e-mail succesfully sent")
            return T('Email succeeded')
Пример #8
0
def send(message, recipient):
    """ Send message if message non-empty and email-parms are set """

    if not message.strip('\n\r\t '):
        return "Skipped empty message"

    if cfg.email_server() and recipient and cfg.email_from():

        message = _prepare_message(message)

        server, port = split_host(cfg.email_server())
        if not port:
            port = 25

        logging.debug("Connecting to server %s:%s", server, port)

        try:
            mailconn = ssmtplib.SMTP_SSL(server, port)
            mailconn.ehlo()

            logging.debug("Connected to server %s:%s", server, port)

        except Exception, errorcode:
            if errorcode[0]:

                # Non SSL mail server
                logging.debug("Non-SSL mail server detected " \
                             "reconnecting to server %s:%s", server, port)

                try:
                    mailconn = smtplib.SMTP(server, port)
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to connect to mail server'))
            else:
                return errormsg(T('Failed to connect to mail server'))

        # TLS support
        if mailconn.ehlo_resp:
            m = re.search('STARTTLS', mailconn.ehlo_resp, re.IGNORECASE)
            if m:
                logging.debug("TLS mail server detected")

                try:
                    mailconn.starttls()
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to initiate TLS connection'))

        # Authentication
        if (cfg.email_account() != "") and (cfg.email_pwd() != ""):
            try:
                mailconn.login(cfg.email_account(), cfg.email_pwd())
            except:
                return errormsg(T('Failed to authenticate to mail server'))

        try:
            mailconn.sendmail(cfg.email_from(), recipient, message)
            msg = None
        except smtplib.SMTPHeloError:
            msg = errormsg('The server didn\'t reply properly to the helo greeting.')
        except smtplib.SMTPRecipientsRefused:
            msg = errormsg('The server rejected ALL recipients (no mail was sent).')
        except smtplib.SMTPSenderRefused:
            msg = errormsg('The server didn\'t accept the from_addr.')
        except smtplib.SMTPDataError:
            msg = errormsg('The server replied with an unexpected error code (other than a refusal of a recipient).')
        except:
            msg = errormsg(T('Failed to send e-mail'))

        try:
            mailconn.close()
        except:
            errormsg(T('Failed to close mail connection'))

        if msg:
            return msg
        else:
            logging.info("Notification e-mail succesfully sent")
            return T('Email succeeded')
Пример #9
0
def send(message, recipient):
    """ Send message if message non-empty and email-parms are set """

    if not message.strip('\n\r\t '):
        return "Skipped empty message"

    if cfg.email_server() and recipient and cfg.email_from():

        message = _prepare_message(message)

        server, port = split_host(cfg.email_server())
        if not port:
            port = 25

        logging.debug("Connecting to server %s:%s", server, port)

        try:
            mailconn = ssmtplib.SMTP_SSL(server, port)
            mailconn.ehlo()

            logging.debug("Connected to server %s:%s", server, port)

        except Exception, errorcode:
            if errorcode[0]:

                # Non SSL mail server
                logging.debug("Non-SSL mail server detected " \
                             "reconnecting to server %s:%s", server, port)

                try:
                    mailconn = smtplib.SMTP(server, port)
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to connect to mail server'))
            else:
                return errormsg(T('Failed to connect to mail server'))

        # TLS support
        if mailconn.ehlo_resp:
            m = re.search('STARTTLS', mailconn.ehlo_resp, re.IGNORECASE)
            if m:
                logging.debug("TLS mail server detected")

                try:
                    mailconn.starttls()
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to initiate TLS connection'))

        # Authentication
        if (cfg.email_account() != "") and (cfg.email_pwd() != ""):
            try:
                mailconn.login(cfg.email_account(), cfg.email_pwd())
            except:
                return errormsg(T('Failed to authenticate to mail server'))

        try:
            mailconn.sendmail(cfg.email_from(), recipient, message)
            msg = None
        except smtplib.SMTPHeloError:
            msg = errormsg(
                'The server didn\'t reply properly to the helo greeting.')
        except smtplib.SMTPRecipientsRefused:
            msg = errormsg(
                'The server rejected ALL recipients (no mail was sent).')
        except smtplib.SMTPSenderRefused:
            msg = errormsg('The server didn\'t accept the from_addr.')
        except smtplib.SMTPDataError:
            msg = errormsg(
                'The server replied with an unexpected error code (other than a refusal of a recipient).'
            )
        except:
            msg = errormsg(T('Failed to send e-mail'))

        try:
            mailconn.close()
        except:
            errormsg(T('Failed to close mail connection'))

        if msg:
            return msg
        else:
            logging.info("Notification e-mail succesfully sent")
            return T('Email succeeded')
Пример #10
0
def send(message, email_to, test=None):
    """ Send message if message non-empty and email-parms are set """

    def utf8(p):
        return p.encode('utf8', 'ignore')

    # we should not use CFG if we are testing. we should use values
    # from UI instead.

    if test:
        email_server = utf8(test.get('email_server'))
        email_from = utf8(test.get('email_from'))
        email_account = utf8(test.get('email_account'))
        email_pwd = utf8(test.get('email_pwd'))
        if email_pwd and not email_pwd.replace('*', ''):
            # If all stars, get stored password instead
            email_pwd = utf8(cfg.email_pwd())
    else:
        email_server = utf8(cfg.email_server())
        email_from = utf8(cfg.email_from())
        email_account = utf8(cfg.email_account())
        email_pwd = utf8(cfg.email_pwd())

    # email_to is replaced at send_with_template, since it can be an array

    if not message.strip('\n\r\t '):
        return "Skipped empty message"

    if email_server and email_to and email_from:

        message = _prepare_message(message)

        server, port = split_host(email_server)
        if not port:
            port = 25

        logging.debug("Connecting to server %s:%s", server, port)

        try:
            mailconn = smtplib.SMTP_SSL(server, port)
            mailconn.ehlo()

            logging.debug("Connected to server %s:%s", server, port)

        except Exception, errorcode:
            if errorcode[0]:

                # Non SSL mail server
                logging.debug("Non-SSL mail server detected "
                             "reconnecting to server %s:%s", server, port)

                try:
                    mailconn = smtplib.SMTP(server, port)
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to connect to mail server'))
            else:
                return errormsg(T('Failed to connect to mail server'))

        # TLS support
        if mailconn.ehlo_resp:
            m = re.search('STARTTLS', mailconn.ehlo_resp, re.IGNORECASE)
            if m:
                logging.debug("TLS mail server detected")

                try:
                    mailconn.starttls()
                    mailconn.ehlo()
                except:
                    return errormsg(T('Failed to initiate TLS connection'))

        # Authentication
        if (email_account != "") and (email_pwd != ""):
            try:
                mailconn.login(email_account, email_pwd)
            except smtplib.SMTPHeloError:
                return errormsg(T("The server didn't reply properly to the helo greeting"))
            except smtplib.SMTPAuthenticationError:
                return errormsg(T("Failed to authenticate to mail server"))
            except smtplib.SMTPException:
                return errormsg(T("No suitable authentication method was found"))
            except:
                return errormsg(T("Unknown authentication failure in mail server"))

        try:
            mailconn.sendmail(email_from, email_to, message)
            msg = None
        except smtplib.SMTPHeloError:
            msg = errormsg('The server didn\'t reply properly to the helo greeting.')
        except smtplib.SMTPRecipientsRefused:
            msg = errormsg('The server rejected ALL recipients (no mail was sent).')
        except smtplib.SMTPSenderRefused:
            msg = errormsg('The server didn\'t accept the from_addr.')
        except smtplib.SMTPDataError:
            msg = errormsg('The server replied with an unexpected error code (other than a refusal of a recipient).')
        except:
            msg = errormsg(T('Failed to send e-mail'))

        try:
            mailconn.close()
        except:
            errormsg(T('Failed to close mail connection'))

        if msg:
            return msg
        else:
            logging.info("Notification e-mail successfully sent")
            return T('Email succeeded')