15 from string
import Template
16 from email.mime.multipart
import MIMEMultipart
17 from email.mime.text
import MIMEText
18 from email.charset
import add_charset, QP
23 def get_greeting(name):
25 Get a random greeting and closing statement using name
55 "greeting":
"{} {}".format(random.choice(greetings), name),
56 "closing": random.choice(closing),
60 def 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 "Unknown mood please use one of {}".format(
", ".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 "{greeting},\n\n{text}{plain_link}\n\n{closing}"
136 "\n\tThe Belle II Software Bot (B2Bot)".format(**data),
144 "validation/html_static/templates/template_mail.html",
148 msg.attach(MIMEText(template.substitute(**data),
"html"))
150 if os.environ.get(
"bamboo_DRYRUN",
False):
152 open(msg[
"To"] +
".html",
"w").write(template.substitute(**data))
157 from mail_config
import sendmail
161 except smtplib.SMTPAuthenticationError
as e:
163 "!!!!!!!!!!!!!!!!!!!!!\n"
164 "AN ERROR OCCURED DURING SENDING OF MAILS:",
167 print(e, file=sys.stderr)
168 print(
"!!!!!!!!!!!!!!!!!!!!!", file=sys.stderr)
171 [
"/usr/sbin/sendmail",
"-t",
"-oi"], input=msg.as_bytes()