moved 2025 to archive
This commit is contained in:
@@ -18,10 +18,9 @@ import logging
|
||||
|
||||
|
||||
# only for develop
|
||||
endDate = (datetime.datetime.now() +
|
||||
datetime.timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
endDate = (datetime.datetime.now() + datetime.timedelta(days=7)).strftime("%Y-%m-%d")
|
||||
|
||||
participoUrl = "http://cwsvjudo.bplaced.net/participo"
|
||||
PARTICIPO_URL = "https://cwsvjudo.de/participo"
|
||||
|
||||
|
||||
class Email:
|
||||
@@ -32,21 +31,21 @@ class Email:
|
||||
self.title = title
|
||||
self.mdText = mdText
|
||||
|
||||
def addApiKeyToUrls(self, apiKey, url=participoUrl):
|
||||
self.mdText = re.sub(url+"([^#,\n]*)", url + "\\1" +
|
||||
"?apiKey="+apiKey, self.mdText)
|
||||
def addApiKeyToUrls(self, apiKey, url=PARTICIPO_URL):
|
||||
self.mdText = re.sub(
|
||||
url + "([^#,\n]*)", url + "\\1" + "&apiKey=" + apiKey, self.mdText
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def loadFromMdFile(path):
|
||||
from yaml import safe_load
|
||||
|
||||
|
||||
# read markdownfile as header and text
|
||||
mdHeader = None
|
||||
with open(argv.mdFilePath) as f:
|
||||
mdHeader = safe_load(get_yaml(f))
|
||||
|
||||
title = mdHeader['title'] if checkHeader(
|
||||
mdHeader) else "cwsvJudo newsLetter"
|
||||
title = mdHeader["title"] if checkHeader(mdHeader) else "cwsvJudo newsLetter"
|
||||
|
||||
mdText = None
|
||||
with open(argv.mdFilePath) as f:
|
||||
@@ -56,16 +55,16 @@ class Email:
|
||||
|
||||
|
||||
def get_yaml(f):
|
||||
'''Extracts the yamlHeader from a Markdown file'''
|
||||
"""Extracts the yamlHeader from a Markdown file"""
|
||||
yamlHeader = None
|
||||
pointer = f.tell()
|
||||
if f.readline() != '---\n':
|
||||
if f.readline() != "---\n":
|
||||
f.seek(pointer)
|
||||
return ''
|
||||
readline = iter(f.readline, '')
|
||||
readline = iter(readline.__next__, '---\n')
|
||||
return ""
|
||||
readline = iter(f.readline, "")
|
||||
readline = iter(readline.__next__, "---\n")
|
||||
|
||||
yamlHeader = ''.join(readline)
|
||||
yamlHeader = "".join(readline)
|
||||
|
||||
return yamlHeader
|
||||
|
||||
@@ -82,34 +81,33 @@ def checkHeader(header):
|
||||
bool: true if header is alright, false if an error was detected
|
||||
"""
|
||||
retVal = True
|
||||
if not 'title' in header:
|
||||
if not "title" in header:
|
||||
logging.info("Header has no 'title' attribute!")
|
||||
retVal = False
|
||||
else:
|
||||
if header['title'] is False:
|
||||
if header["title"] is False:
|
||||
logging.info("Empty title!")
|
||||
retVal = False
|
||||
return retVal
|
||||
|
||||
|
||||
def getArguments():
|
||||
argParser = argparse.ArgumentParser(
|
||||
description="Send an Markdown-File as eMail"
|
||||
argParser = argparse.ArgumentParser(description="Send an Markdown-File as eMail")
|
||||
argParser.add_argument("mdFilePath", help="Path to MarkdownFile to send")
|
||||
argParser.add_argument("-r", "--receiver", help="json file with the receiver")
|
||||
argParser.add_argument("--dontSend", action="store_true")
|
||||
argParser.add_argument(
|
||||
"-c",
|
||||
"--config",
|
||||
nargs="+",
|
||||
type=argparse.FileType("r"),
|
||||
help="yaml formatted config file(s)",
|
||||
)
|
||||
argParser.add_argument(
|
||||
"mdFilePath",
|
||||
help="Path to MarkdownFile to send"
|
||||
)
|
||||
argParser.add_argument(
|
||||
"-r", "--receiver", help="json file with the receiver")
|
||||
argParser.add_argument(
|
||||
"--dontSend",
|
||||
action="store_true"
|
||||
)
|
||||
argParser.add_argument(
|
||||
"-c", "--config",
|
||||
nargs="+", type=argparse.FileType("r"),
|
||||
help="yaml formatted config file(s)"
|
||||
"-p",
|
||||
"--participoUrl",
|
||||
help="url for the participo app (e.g. indicator for appending the personal apiKey to the event url)",
|
||||
default=PARTICIPO_URL,
|
||||
)
|
||||
|
||||
return argParser.parse_args()
|
||||
@@ -125,7 +123,7 @@ def loadFromJson(path):
|
||||
|
||||
def loadFromYamlFile(yamlFile):
|
||||
from yaml import safe_load
|
||||
|
||||
|
||||
with yamlFile as f:
|
||||
return safe_load(yamlFile)
|
||||
|
||||
@@ -142,17 +140,16 @@ def createApiKey(allowKey, userId, rights, endDate):
|
||||
return: new api key or none on failure
|
||||
"""
|
||||
postData = {
|
||||
'apiKey': allowKey,
|
||||
'userId': userId,
|
||||
'rights': rights,
|
||||
'endDate': endDate
|
||||
"apiKey": allowKey,
|
||||
"userId": userId,
|
||||
"rights": rights,
|
||||
"endDate": endDate,
|
||||
}
|
||||
response = requests.post(
|
||||
participoUrl+"/api.apiKeys.add", json=postData)
|
||||
response = requests.post(argv.participoUrl + "/api.apiKeys.add", json=postData)
|
||||
|
||||
jsonResponse = response.json()
|
||||
|
||||
return jsonResponse['apiKey'] if 'apiKey' else None
|
||||
return jsonResponse["apiKey"] if "apiKey" else None
|
||||
|
||||
|
||||
def randomSleep(min=60, max=600):
|
||||
@@ -181,9 +178,15 @@ if __name__ == "__main__":
|
||||
|
||||
for user in receivers:
|
||||
apiKey = createApiKey(
|
||||
config['apiKey']['createApiKey'], user['id'], "login", endDate)
|
||||
config["apiKey"]["createApiKey"],
|
||||
user.get("userId", user.get("id")),
|
||||
"login",
|
||||
endDate,
|
||||
)
|
||||
if apiKey is None:
|
||||
logging.info(f"Couldn't get apiKey for apiKey creation! Ok if no apiKey needs to be created.")
|
||||
logging.error(
|
||||
f"Failed to create apiKey for user {user['id']} ({user['loginName']})"
|
||||
)
|
||||
continue
|
||||
|
||||
email = Email.loadFromMdFile(argv.mdFilePath) # emailTemplate
|
||||
@@ -193,23 +196,31 @@ if __name__ == "__main__":
|
||||
# text = pypandoc.convert_text(email.mdText, "plain", format='md', extra_args=[
|
||||
# "--self-contained", "--resource-path=../aufgaben"])
|
||||
# plain text did swallow the Url. As workaround we are trying markdown for the plain text
|
||||
text = pypandoc.convert_text(email.mdText, "markdown", format='md', extra_args=[
|
||||
"--self-contained", "--resource-path=../aufgaben"])
|
||||
html = pypandoc.convert_text(email.mdText, "html", format='md', extra_args=[
|
||||
"--self-contained", "--resource-path=../aufgaben"])
|
||||
text = pypandoc.convert_text(
|
||||
email.mdText,
|
||||
"markdown",
|
||||
format="md",
|
||||
extra_args=["--self-contained", "--resource-path=../aufgaben"],
|
||||
)
|
||||
html = pypandoc.convert_text(
|
||||
email.mdText,
|
||||
"html",
|
||||
format="md",
|
||||
extra_args=["--self-contained", "--resource-path=../aufgaben"],
|
||||
)
|
||||
|
||||
# Turn these into plain/html MIMEText objects
|
||||
txtMimeText = MIMEText(text, "plain")
|
||||
htmlMimeText = MIMEText(html, "html")
|
||||
|
||||
# @todo the message has to be recreated for every email address since it seems to be added by reference to the queue. meaning changing the emailAddress changes it in the previously added also
|
||||
for toAddress in user['eMail']:
|
||||
for toAddress in user["eMail"]:
|
||||
# create the mail
|
||||
message = MIMEMultipart("alternative")
|
||||
# Setting header data
|
||||
message["Subject"] = email.title
|
||||
message["From"] = config['senderEmailAddress']
|
||||
message["Reply-To"] = config['senderEmailAddress']
|
||||
message["From"] = config["senderEmailAddress"]
|
||||
message["Reply-To"] = config["senderEmailAddress"]
|
||||
message["Date"] = str(utils.formatdate(localtime=True))
|
||||
|
||||
# only set the to-header one time: setting it multiple
|
||||
@@ -231,18 +242,21 @@ if __name__ == "__main__":
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
|
||||
|
||||
for message in messageQueue:
|
||||
# randomSleep(min=10, max=20)
|
||||
|
||||
with smtplib.SMTP_SSL(config['smtp']['serverAddress'], config['smtp']['serverPort'], context=context) as server:
|
||||
server.login(config['smtp']['login'], config['smtp']['password'])
|
||||
with smtplib.SMTP_SSL(
|
||||
config["smtp"]["serverAddress"],
|
||||
config["smtp"]["serverPort"],
|
||||
context=context,
|
||||
) as server:
|
||||
server.login(config["smtp"]["login"], config["smtp"]["password"])
|
||||
if not argv.dontSend:
|
||||
logging.info(f"sending to {message['To']}")
|
||||
server.sendmail(
|
||||
from_addr=config['senderEmailAddress'],
|
||||
from_addr=config["senderEmailAddress"],
|
||||
to_addrs=message["To"],
|
||||
msg=message.as_string()
|
||||
msg=message.as_string(),
|
||||
)
|
||||
# except smtplib.SMTPSenderRefused as exception:
|
||||
# if exception.smtp_code == 450:
|
||||
@@ -250,4 +264,3 @@ if __name__ == "__main__":
|
||||
# time.sleep(60 * 60)
|
||||
# server.login(config['smtp']['login'], config['smtp']['password'])
|
||||
# logging.error(f"Unexpected SMTPSenderRefused exception: {exception} - {repr(exception)}")
|
||||
|
||||
Reference in New Issue
Block a user