# Buggy code
def _send_raw_email(self):
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.queue[index]["starttime"] = datetime.now()
    self.UIqueue[index]["formStarttime"] = self.queue[index]["starttime"]
    self.UIqueue[index]["stat"] = STAT_STARTED
    obj = self.queue[index]
    # create MIME message
    msg = MIMEMultipart()
    msg["Subject"] = self.queue[index]["subject"]
    msg["Message-Id"] = make_msgid("calibre-web")
    msg["Date"] = formatdate(localtime=True)
    text = self.queue[index]["text"]
    msg.attach(MIMEText(text.encode("UTF-8"), "plain", "UTF-8"))
    if obj["attachment"]:
        result = get_attachment(obj["filepath"], obj["attachment"])
        if result:
            msg.attach(result)
        else:
            self._handleError("Attachment not found")
            return

    msg["From"] = obj["settings"]["mail_from"]
    msg["To"] = obj["recipent"]

    use_ssl = int(obj["settings"].get("mail_use_ssl", 0))
    try:
        # convert MIME message to string
        fp = StringIO()
        gen = Generator(fp, mangle_from_=False)
        gen.flatten(msg)
        msg = fp.getvalue()

        # send email
        timeout = 600  # set timeout to 5mins

        # redirect output to logfile on python2 pn python3 debugoutput is caught with overwritten
        # _print_debug function
        if sys.version_info < (3, 0):
            org_smtpstderr = smtplib.stderr
            smtplib.stderr = logger.StderrLogger("worker.smtp")

        if use_ssl == 2:
            self.asyncSMTP = email_SSL(
                obj["settings"]["mail_server"], obj["settings"]["mail_port"], timeout
            )
        else:
            self.asyncSMTP = email(
                obj["settings"]["mail_server"], obj["settings"]["mail_port"], timeout
            )

        # link to logginglevel
        if logger.is_debug_enabled():
            self.asyncSMTP.set_debuglevel(1)
        if use_ssl == 1:
            self.asyncSMTP.starttls()
        if obj["settings"]["mail_password"]:
            self.asyncSMTP.login(
                str(obj["settings"]["mail_login"]),
                str(obj["settings"]["mail_password"]),
            )
        self.asyncSMTP.sendmail(obj["settings"]["mail_from"], obj["recipent"], msg)
        self.asyncSMTP.quit()
        self._handleSuccess()

        if sys.version_info < (3, 0):
            smtplib.stderr = org_smtpstderr

    except MemoryError as e:
        self._handleError("Error sending email: " + e.message)
        return None
    except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
        if hasattr(e, "smtp_error"):
            text = e.smtp_error.decode("utf-8").replace("\n", ". ")
        elif hasattr(e, "message"):
            text = e.message
        else:
            text = ""
        self._handleError("Error sending email: " + text)
        return None
    except socket.error as e:
        self._handleError("Error sending email: " + e.strerror)
        return None


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _send_raw_email(self):
    self.doLock.acquire()
    index = self.current
    self.doLock.release()
    self.queue[index]["starttime"] = datetime.now()
    self.UIqueue[index]["formStarttime"] = self.queue[index]["starttime"]
    self.UIqueue[index]["stat"] = STAT_STARTED
    obj = self.queue[index]
    # create MIME message
    msg = MIMEMultipart()
    msg["Subject"] = self.queue[index]["subject"]
    msg["Message-Id"] = make_msgid("calibre-web")
    msg["Date"] = formatdate(localtime=True)
    text = self.queue[index]["text"]
    msg.attach(MIMEText(text.encode("UTF-8"), "plain", "UTF-8"))
    if obj["attachment"]:
        result = get_attachment(obj["filepath"], obj["attachment"])
        if result:
            msg.attach(result)
        else:
            self._handleError("Attachment not found")
            return

    msg["From"] = obj["settings"]["mail_from"]
    msg["To"] = obj["recipent"]

    use_ssl = int(obj["settings"].get("mail_use_ssl", 0))
    try:
        # convert MIME message to string
        fp = StringIO()
        gen = Generator(fp, mangle_from_=False)
        gen.flatten(msg)
        msg = fp.getvalue()

        # send email
        timeout = 600  # set timeout to 5mins

        # redirect output to logfile on python2 pn python3 debugoutput is caught with overwritten
        # _print_debug function
        if sys.version_info < (3, 0):
            org_smtpstderr = smtplib.stderr
            smtplib.stderr = logger.StderrLogger("worker.smtp")

        if use_ssl == 2:
            self.asyncSMTP = email_SSL(
                obj["settings"]["mail_server"], obj["settings"]["mail_port"], timeout
            )
        else:
            self.asyncSMTP = email(
                obj["settings"]["mail_server"], obj["settings"]["mail_port"], timeout
            )

        # link to logginglevel
        if logger.is_debug_enabled():
            self.asyncSMTP.set_debuglevel(1)
        if use_ssl == 1:
            self.asyncSMTP.starttls()
        if obj["settings"]["mail_password"]:
            self.asyncSMTP.login(
                str(obj["settings"]["mail_login"]),
                str(obj["settings"]["mail_password"]),
            )
        self.asyncSMTP.sendmail(obj["settings"]["mail_from"], obj["recipent"], msg)
        self.asyncSMTP.quit()
        self._handleSuccess()

        if sys.version_info < (3, 0):
            smtplib.stderr = org_smtpstderr

    except MemoryError as e:
        self._handleError("Error sending email: " + e.message)
        return None
    except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
        if hasattr(e, "smtp_error"):
            text = e.smtp_error.decode("utf-8").replace("\n", ". ")
        elif hasattr(e, "message"):
            text = e.message
        else:
            text = ""
        self._handleError("Error sending email: " + text)
        return None
    except socket.error as e:
        self._handleError("Error sending email: " + e.strerror)
        return None