15from string
import Template
16from email.mime.multipart
import MIMEMultipart
17from email.mime.text
import MIMEText
18from email.charset
import add_charset, QP
23def get_greeting(name):
25 Get a random greeting and closing statement using name
55 "greeting": f
"{random.choice(greetings)} {name}",
56 "closing": random.choice(closing),
60def markdown_to_plaintext(text):
62 removes markdown specific formatting elements from text
65 replace_links = re.compile(
r"\[.*?]\(([^)]*)\)")
66 text = replace_links.sub(
r"\1", text)
68 replace_attrs = re.compile(
r"\{:([^\}\n]*?)\}")
69 text = replace_attrs.sub(
r"", text)
71 replace_autolink = re.compile(
r"<(https?://[^>]*|[^> ]+@[^> ]+)>")
72 text = replace_autolink.sub(
r"\1", text)
77 name, recipient, subject, text, link=None, link_title=None, mood="normal"
80 Send an email to `name` at mail address `recipient` with the given subject
and text.
82 This function will add a greeting at the top
and a closing statement at the
83 bottom
and convert the mail text to html using markdown.
85 The optional link/link_title argument can be used to easily add a link to
86 the mail
for users to click.
88 all_moods = ["happy",
"normal",
"meh",
"angry",
"livid",
"dead"]
89 if mood
not in all_moods:
91 f
"Unknown mood please use one of {', '.join(all_moods)}"
94 add_charset(
"utf-8", QP, QP,
"utf-8")
95 msg = MIMEMultipart(
"alternative")
96 msg[
"Subject"] = subject
97 msg[
"From"] =
"B2Bot <b2soft@mail.desy.de>"
99 "bamboo_email_override" in os.environ
100 and os.environ[
"bamboo_email_override"].find(
"@") > 0
102 msg[
"To"] = os.environ[
"bamboo_email_override"]
104 msg[
"To"] = recipient
107 "bamboo_email_bcc" in os.environ
108 and os.environ[
"bamboo_email_bcc"].find(
"@") > 0
110 msg[
"Bcc"] = os.environ[
"bamboo_email_bcc"]
112 data = get_greeting(name)
114 data[
"title"] = subject
115 data[
"text"] = markdown_to_plaintext(text)
116 data[
"plain_link"] =
""
119 if link_title
is not None:
120 text += f
"\n\n[{link_title}]({link}){{:.goto}}"
121 data[
"plain_link"] = f
"\n\n{link_title}: {link}"
123 text += f
"\n\n<{link}>{{:.goto}}"
124 data[
"plain_link"] = f
"\n\n{link}"
127 data[
"body"] = markdown.markdown(
129 output_format=
"xhtml1",
130 extensions=[
"markdown.extensions.attr_list"],
135 f
'{data["greeting"]},\n\n{data["text"]}{data["plain_link"]}\n\n{data["closing"]}\n\tThe Belle II Software Bot (B2Bot)',
143 "validation/html_static/templates/template_mail.html",
147 msg.attach(MIMEText(template.substitute(**data),
"html"))
149 if os.environ.get(
"bamboo_DRYRUN",
False):
151 open(msg[
"To"] +
".html",
"w").write(template.substitute(**data))
156 from mail_config
import sendmail
160 except smtplib.SMTPAuthenticationError
as e:
162 "!!!!!!!!!!!!!!!!!!!!!\n"
163 "AN ERROR OCCURRED DURING SENDING OF MAILS:",
166 print(e, file=sys.stderr)
167 print(
"!!!!!!!!!!!!!!!!!!!!!", file=sys.stderr)
170 [
"/usr/sbin/sendmail",
"-t",
"-oi"], input=msg.as_bytes()