2020-08-23 02:44:28 +00:00
|
|
|
from __future__ import division, print_function, unicode_literals
|
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
import smtplib
|
|
|
|
import threading
|
|
|
|
import socket
|
2021-03-28 12:50:55 +00:00
|
|
|
import mimetypes
|
|
|
|
import base64
|
2020-08-23 02:44:28 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
from StringIO import StringIO
|
|
|
|
from email.MIMEBase import MIMEBase
|
|
|
|
from email.MIMEMultipart import MIMEMultipart
|
|
|
|
from email.MIMEText import MIMEText
|
|
|
|
except ImportError:
|
|
|
|
from io import StringIO
|
|
|
|
from email.mime.base import MIMEBase
|
|
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
from email.mime.text import MIMEText
|
|
|
|
|
2021-03-28 12:50:55 +00:00
|
|
|
|
|
|
|
|
2020-08-23 02:44:28 +00:00
|
|
|
from email import encoders
|
|
|
|
from email.utils import formatdate, make_msgid
|
|
|
|
from email.generator import Generator
|
|
|
|
|
|
|
|
from cps.services.worker import CalibreTask
|
2021-03-28 12:50:55 +00:00
|
|
|
from cps.services import gmail
|
2020-08-23 02:44:28 +00:00
|
|
|
from cps import logger, config
|
|
|
|
|
|
|
|
from cps import gdriveutils
|
|
|
|
|
|
|
|
log = logger.create()
|
|
|
|
|
2020-08-23 03:35:48 +00:00
|
|
|
CHUNKSIZE = 8192
|
2020-08-23 02:44:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Class for sending email with ability to get current progress
|
2020-08-23 03:35:48 +00:00
|
|
|
class EmailBase:
|
2020-08-23 02:44:28 +00:00
|
|
|
|
|
|
|
transferSize = 0
|
|
|
|
progress = 0
|
|
|
|
|
|
|
|
def data(self, msg):
|
|
|
|
self.transferSize = len(msg)
|
|
|
|
(code, resp) = smtplib.SMTP.data(self, msg)
|
|
|
|
self.progress = 0
|
|
|
|
return (code, resp)
|
|
|
|
|
|
|
|
def send(self, strg):
|
|
|
|
"""Send `strg' to the server."""
|
2021-01-03 18:27:24 +00:00
|
|
|
log.debug_no_auth('send: {}'.format(strg[:300]))
|
2020-08-23 02:44:28 +00:00
|
|
|
if hasattr(self, 'sock') and self.sock:
|
|
|
|
try:
|
|
|
|
if self.transferSize:
|
|
|
|
lock=threading.Lock()
|
|
|
|
lock.acquire()
|
|
|
|
self.transferSize = len(strg)
|
|
|
|
lock.release()
|
2020-08-23 03:35:48 +00:00
|
|
|
for i in range(0, self.transferSize, CHUNKSIZE):
|
2020-08-23 02:44:28 +00:00
|
|
|
if isinstance(strg, bytes):
|
2020-08-23 03:35:48 +00:00
|
|
|
self.sock.send((strg[i:i + CHUNKSIZE]))
|
2020-08-23 02:44:28 +00:00
|
|
|
else:
|
2020-08-23 03:35:48 +00:00
|
|
|
self.sock.send((strg[i:i + CHUNKSIZE]).encode('utf-8'))
|
2020-08-23 02:44:28 +00:00
|
|
|
lock.acquire()
|
|
|
|
self.progress = i
|
|
|
|
lock.release()
|
|
|
|
else:
|
|
|
|
self.sock.sendall(strg.encode('utf-8'))
|
|
|
|
except socket.error:
|
|
|
|
self.close()
|
|
|
|
raise smtplib.SMTPServerDisconnected('Server not connected')
|
|
|
|
else:
|
|
|
|
raise smtplib.SMTPServerDisconnected('please run connect() first')
|
|
|
|
|
|
|
|
@classmethod
|
2020-08-23 03:35:48 +00:00
|
|
|
def _print_debug(cls, *args):
|
2020-08-23 02:44:28 +00:00
|
|
|
log.debug(args)
|
|
|
|
|
|
|
|
def getTransferStatus(self):
|
|
|
|
if self.transferSize:
|
|
|
|
lock2 = threading.Lock()
|
|
|
|
lock2.acquire()
|
|
|
|
value = int((float(self.progress) / float(self.transferSize))*100)
|
|
|
|
lock2.release()
|
2020-08-23 03:35:48 +00:00
|
|
|
return value / 100
|
2020-08-23 02:44:28 +00:00
|
|
|
else:
|
2020-08-23 03:35:48 +00:00
|
|
|
return 1
|
2020-08-23 02:44:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Class for sending email with ability to get current progress, derived from emailbase class
|
|
|
|
class Email(EmailBase, smtplib.SMTP):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
smtplib.SMTP.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
# Class for sending ssl encrypted email with ability to get current progress, , derived from emailbase class
|
|
|
|
class EmailSSL(EmailBase, smtplib.SMTP_SSL):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
smtplib.SMTP_SSL.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class TaskEmail(CalibreTask):
|
2021-03-28 12:50:55 +00:00
|
|
|
def __init__(self, subject, filepath, attachment, settings, recipient, taskMessage, text):
|
2020-08-24 01:21:55 +00:00
|
|
|
super(TaskEmail, self).__init__(taskMessage)
|
2020-08-23 02:44:28 +00:00
|
|
|
self.subject = subject
|
|
|
|
self.attachment = attachment
|
|
|
|
self.settings = settings
|
|
|
|
self.filepath = filepath
|
|
|
|
self.recipent = recipient
|
|
|
|
self.text = text
|
2020-08-23 03:35:48 +00:00
|
|
|
self.asyncSMTP = None
|
2020-08-23 02:44:28 +00:00
|
|
|
self.results = dict()
|
|
|
|
|
2021-03-21 07:19:54 +00:00
|
|
|
def prepare_message(self):
|
2021-03-28 12:50:55 +00:00
|
|
|
message = MIMEMultipart()
|
|
|
|
message['to'] = self.recipent
|
|
|
|
message['from'] = self.settings["mail_from"]
|
|
|
|
message['subject'] = self.subject
|
|
|
|
message['Message-Id'] = make_msgid('calibre-web')
|
|
|
|
message['Date'] = formatdate(localtime=True)
|
2020-08-23 02:44:28 +00:00
|
|
|
text = self.text
|
2021-03-28 12:50:55 +00:00
|
|
|
msg = MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
|
|
|
|
message.attach(msg)
|
2020-08-23 02:44:28 +00:00
|
|
|
if self.attachment:
|
2020-08-23 03:35:48 +00:00
|
|
|
result = self._get_attachment(self.filepath, self.attachment)
|
2020-08-23 02:44:28 +00:00
|
|
|
if result:
|
2021-03-28 12:50:55 +00:00
|
|
|
message.attach(result)
|
2020-08-23 02:44:28 +00:00
|
|
|
else:
|
|
|
|
self._handleError(u"Attachment not found")
|
|
|
|
return
|
2021-03-28 12:50:55 +00:00
|
|
|
return message
|
2021-03-21 07:19:54 +00:00
|
|
|
|
|
|
|
def run(self, worker_thread):
|
|
|
|
# create MIME message
|
|
|
|
msg = self.prepare_message()
|
2020-08-23 02:44:28 +00:00
|
|
|
try:
|
2021-03-28 12:50:55 +00:00
|
|
|
if self.settings['mail_server_type'] == 0:
|
|
|
|
self.send_standard_email(msg)
|
2020-08-23 02:44:28 +00:00
|
|
|
else:
|
2021-03-28 12:50:55 +00:00
|
|
|
self.send_gmail_email(msg)
|
|
|
|
except MemoryError as e:
|
2020-12-12 07:11:00 +00:00
|
|
|
log.debug_or_exception(e)
|
2021-03-28 12:50:55 +00:00
|
|
|
self._handleError(u'MemoryError sending email: {}'.format(str(e)))
|
2020-08-23 02:44:28 +00:00
|
|
|
except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
|
2021-03-21 10:54:39 +00:00
|
|
|
log.debug_or_exception(e)
|
2020-08-23 02:44:28 +00:00
|
|
|
if hasattr(e, "smtp_error"):
|
|
|
|
text = e.smtp_error.decode('utf-8').replace("\n", '. ')
|
|
|
|
elif hasattr(e, "message"):
|
|
|
|
text = e.message
|
2020-08-30 11:43:08 +00:00
|
|
|
elif hasattr(e, "args"):
|
|
|
|
text = '\n'.join(e.args)
|
2020-08-23 02:44:28 +00:00
|
|
|
else:
|
|
|
|
text = ''
|
2021-03-28 12:50:55 +00:00
|
|
|
self._handleError(u'Smtplib Error sending email: {}'.format(text))
|
|
|
|
except socket.error as e:
|
|
|
|
log.debug_or_exception(e)
|
|
|
|
self._handleError(u'Socket Error sending email: {}'.format(e.strerror))
|
|
|
|
except Exception as e:
|
2021-03-21 10:54:39 +00:00
|
|
|
log.debug_or_exception(e)
|
2021-03-28 12:50:55 +00:00
|
|
|
self._handleError(u'Error sending email: {}'.format(e))
|
|
|
|
|
|
|
|
|
|
|
|
def send_standard_email(self, msg):
|
|
|
|
use_ssl = int(self.settings.get('mail_use_ssl', 0))
|
|
|
|
timeout = 600 # set timeout to 5mins
|
2020-10-04 11:59:33 +00:00
|
|
|
|
2021-03-28 12:50:55 +00:00
|
|
|
# redirect output to logfile on python2 on 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 = EmailSSL(self.settings["mail_server"], self.settings["mail_port"],
|
|
|
|
timeout=timeout)
|
|
|
|
else:
|
|
|
|
self.asyncSMTP = Email(self.settings["mail_server"], self.settings["mail_port"], timeout=timeout)
|
|
|
|
|
|
|
|
# link to logginglevel
|
|
|
|
if logger.is_debug_enabled():
|
|
|
|
self.asyncSMTP.set_debuglevel(1)
|
|
|
|
if use_ssl == 1:
|
|
|
|
self.asyncSMTP.starttls()
|
|
|
|
if self.settings["mail_password"]:
|
|
|
|
self.asyncSMTP.login(str(self.settings["mail_login"]), str(self.settings["mail_password"]))
|
|
|
|
|
|
|
|
# Convert message to something to send
|
|
|
|
fp = StringIO()
|
|
|
|
gen = Generator(fp, mangle_from_=False)
|
|
|
|
gen.flatten(msg)
|
|
|
|
|
|
|
|
self.asyncSMTP.sendmail(self.settings["mail_from"], self.recipent, fp.getvalue())
|
|
|
|
self.asyncSMTP.quit()
|
|
|
|
self._handleSuccess()
|
|
|
|
|
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
smtplib.stderr = org_smtpstderr
|
|
|
|
|
|
|
|
|
|
|
|
def send_gmail_email(self, message):
|
|
|
|
return gmail.send_messsage(self.settings.get('mail_gmail_token', None), message)
|
2020-08-23 02:44:28 +00:00
|
|
|
|
2020-08-23 03:35:48 +00:00
|
|
|
@property
|
|
|
|
def progress(self):
|
|
|
|
if self.asyncSMTP is not None:
|
|
|
|
return self.asyncSMTP.getTransferStatus()
|
|
|
|
else:
|
2020-08-23 16:58:24 +00:00
|
|
|
return self._progress
|
|
|
|
|
|
|
|
@progress.setter
|
|
|
|
def progress(self, x):
|
|
|
|
"""This gets explicitly set when handle(Success|Error) are called. In this case, remove the SMTP connection"""
|
|
|
|
if x == 1:
|
|
|
|
self.asyncSMTP = None
|
|
|
|
self._progress = x
|
|
|
|
|
2020-08-23 03:35:48 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _get_attachment(cls, bookpath, filename):
|
2020-08-23 02:44:28 +00:00
|
|
|
"""Get file as MIMEBase message"""
|
2021-03-28 12:50:55 +00:00
|
|
|
calibre_path = config.config_calibre_dir
|
2020-08-23 02:44:28 +00:00
|
|
|
if config.config_use_google_drive:
|
|
|
|
df = gdriveutils.getFileFromEbooksFolder(bookpath, filename)
|
|
|
|
if df:
|
2021-03-28 12:50:55 +00:00
|
|
|
datafile = os.path.join(calibre_path, bookpath, filename)
|
|
|
|
if not os.path.exists(os.path.join(calibre_path, bookpath)):
|
|
|
|
os.makedirs(os.path.join(calibre_path, bookpath))
|
2020-08-23 02:44:28 +00:00
|
|
|
df.GetContentFile(datafile)
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
file_ = open(datafile, 'rb')
|
|
|
|
data = file_.read()
|
|
|
|
file_.close()
|
|
|
|
os.remove(datafile)
|
|
|
|
else:
|
|
|
|
try:
|
2021-03-28 12:50:55 +00:00
|
|
|
file_ = open(os.path.join(calibre_path, bookpath, filename), 'rb')
|
2020-08-23 02:44:28 +00:00
|
|
|
data = file_.read()
|
|
|
|
file_.close()
|
|
|
|
except IOError as e:
|
2020-12-12 07:11:00 +00:00
|
|
|
log.debug_or_exception(e)
|
2020-08-23 02:44:28 +00:00
|
|
|
log.error(u'The requested file could not be read. Maybe wrong permissions?')
|
|
|
|
return None
|
2021-03-28 12:50:55 +00:00
|
|
|
# Set mimetype
|
|
|
|
content_type, encoding = mimetypes.guess_type(filename)
|
|
|
|
if content_type is None or encoding is not None:
|
|
|
|
content_type = 'application/octet-stream'
|
|
|
|
main_type, sub_type = content_type.split('/', 1)
|
|
|
|
attachment = MIMEBase(main_type, sub_type)
|
2020-08-23 02:44:28 +00:00
|
|
|
attachment.set_payload(data)
|
|
|
|
encoders.encode_base64(attachment)
|
2021-03-28 12:50:55 +00:00
|
|
|
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
|
2020-08-23 02:44:28 +00:00
|
|
|
return attachment
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
|
|
|
return "Email"
|