| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2012, Dag Wieers (@dagwieers) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
author: |
| 11 |
- Dag Wieers (@dagwieers) |
| 12 |
module: mail |
| 13 |
short_description: Send an email |
| 14 |
description: |
| 15 |
- This module is useful for sending emails from playbooks. |
| 16 |
- One may wonder why automate sending emails? In complex environments there are from time to time processes that cannot |
| 17 |
be automated, either because you lack the authority to make it so, or because not everyone agrees to a common approach. |
| 18 |
- If you cannot automate a specific step, but the step is non-blocking, sending out an email to the responsible party to |
| 19 |
make them perform their part of the bargain is an elegant way to put the responsibility in someone else's lap. |
| 20 |
- Of course sending out a mail can be equally useful as a way to notify one or more people in a team that a specific action |
| 21 |
has been (successfully) taken. |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.general._attributes |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: none |
| 27 |
diff_mode: |
| 28 |
support: none |
| 29 |
options: |
| 30 |
sender: |
| 31 |
description: |
| 32 |
- The email-address the mail is sent from. May contain address and phrase. |
| 33 |
type: str |
| 34 |
default: root |
| 35 |
aliases: [from] |
| 36 |
to: |
| 37 |
description: |
| 38 |
- The email-address(es) the mail is being sent to. |
| 39 |
- This is a list, which may contain address and phrase portions. |
| 40 |
type: list |
| 41 |
elements: str |
| 42 |
default: root |
| 43 |
aliases: [recipients] |
| 44 |
cc: |
| 45 |
description: |
| 46 |
- The email-address(es) the mail is being copied to. |
| 47 |
- This is a list, which may contain address and phrase portions. |
| 48 |
type: list |
| 49 |
elements: str |
| 50 |
default: [] |
| 51 |
bcc: |
| 52 |
description: |
| 53 |
- The email-address(es) the mail is being 'blind' copied to. |
| 54 |
- This is a list, which may contain address and phrase portions. |
| 55 |
type: list |
| 56 |
elements: str |
| 57 |
default: [] |
| 58 |
subject: |
| 59 |
description: |
| 60 |
- The subject of the email being sent. |
| 61 |
required: true |
| 62 |
type: str |
| 63 |
aliases: [msg] |
| 64 |
body: |
| 65 |
description: |
| 66 |
- The body of the email being sent. |
| 67 |
type: str |
| 68 |
username: |
| 69 |
description: |
| 70 |
- If SMTP requires username. |
| 71 |
type: str |
| 72 |
password: |
| 73 |
description: |
| 74 |
- If SMTP requires password. |
| 75 |
type: str |
| 76 |
host: |
| 77 |
description: |
| 78 |
- The mail server. |
| 79 |
type: str |
| 80 |
default: localhost |
| 81 |
port: |
| 82 |
description: |
| 83 |
- The mail server port. |
| 84 |
- This must be a valid integer between V(1) and V(65534). |
| 85 |
type: int |
| 86 |
default: 25 |
| 87 |
attach: |
| 88 |
description: |
| 89 |
- A list of pathnames of files to attach to the message. |
| 90 |
- Attached files have their content-type set to C(application/octet-stream). |
| 91 |
type: list |
| 92 |
elements: path |
| 93 |
default: [] |
| 94 |
headers: |
| 95 |
description: |
| 96 |
- A list of headers which should be added to the message. |
| 97 |
- Each individual header is specified as V(header=value) (see example below). |
| 98 |
type: list |
| 99 |
elements: str |
| 100 |
default: [] |
| 101 |
charset: |
| 102 |
description: |
| 103 |
- The character set of email being sent. |
| 104 |
type: str |
| 105 |
default: utf-8 |
| 106 |
subtype: |
| 107 |
description: |
| 108 |
- The minor mime type, can be either V(plain) or V(html). |
| 109 |
- The major type is always V(text). |
| 110 |
type: str |
| 111 |
choices: [html, plain] |
| 112 |
default: plain |
| 113 |
secure: |
| 114 |
description: |
| 115 |
- If V(always), the connection only sends email if the connection is Encrypted. If the server does not accept the encrypted |
| 116 |
connection it fails. |
| 117 |
- If V(try), the connection attempts to setup a secure SSL/TLS session, before trying to send. |
| 118 |
- If V(never), the connection does not attempt to setup a secure SSL/TLS session, before sending. |
| 119 |
- If V(starttls), the connection tries to upgrade to a secure SSL/TLS connection, before sending. If it is unable to |
| 120 |
do so it fails. |
| 121 |
type: str |
| 122 |
choices: [always, never, starttls, try] |
| 123 |
default: try |
| 124 |
timeout: |
| 125 |
description: |
| 126 |
- Sets the timeout in seconds for connection attempts. |
| 127 |
type: int |
| 128 |
default: 20 |
| 129 |
ehlohost: |
| 130 |
description: |
| 131 |
- Allows for manual specification of host for EHLO. |
| 132 |
type: str |
| 133 |
version_added: 3.8.0 |
| 134 |
message_id_domain: |
| 135 |
description: |
| 136 |
- The domain name to use for the L(Message-ID header, https://en.wikipedia.org/wiki/Message-ID). |
| 137 |
type: str |
| 138 |
default: ansible |
| 139 |
version_added: 8.2.0 |
| 140 |
""" |
| 141 |
|
| 142 |
EXAMPLES = r""" |
| 143 |
- name: Example playbook sending mail to root |
| 144 |
community.general.mail: |
| 145 |
subject: System {{ ansible_hostname }} has been successfully provisioned. |
| 146 |
delegate_to: localhost |
| 147 |
|
| 148 |
- name: Sending an e-mail using Gmail SMTP servers |
| 149 |
community.general.mail: |
| 150 |
host: smtp.gmail.com |
| 151 |
port: 587 |
| 152 |
username: [email protected] |
| 153 |
password: mysecret |
| 154 |
to: John Smith <[email protected]> |
| 155 |
subject: Ansible-report |
| 156 |
body: System {{ ansible_hostname }} has been successfully provisioned. |
| 157 |
delegate_to: localhost |
| 158 |
|
| 159 |
- name: Send e-mail to a bunch of users, attaching files |
| 160 |
community.general.mail: |
| 161 |
host: 127.0.0.1 |
| 162 |
port: 2025 |
| 163 |
subject: Ansible-report |
| 164 |
body: Hello, this is an e-mail. I hope you like it ;-) |
| 165 |
from: [email protected] (Jane Jolie) |
| 166 |
to: |
| 167 |
- John Doe <[email protected]> |
| 168 |
- Suzie Something <[email protected]> |
| 169 |
cc: Charlie Root <root@localhost> |
| 170 |
attach: |
| 171 |
- /etc/group |
| 172 |
- /tmp/avatar2.png |
| 173 |
headers: |
| 174 |
- [email protected] |
| 175 |
- X-Special="Something or other" |
| 176 |
charset: us-ascii |
| 177 |
delegate_to: localhost |
| 178 |
|
| 179 |
- name: Sending an e-mail using the remote machine, not the Ansible controller node |
| 180 |
community.general.mail: |
| 181 |
host: localhost |
| 182 |
port: 25 |
| 183 |
to: John Smith <[email protected]> |
| 184 |
subject: Ansible-report |
| 185 |
body: System {{ ansible_hostname }} has been successfully provisioned. |
| 186 |
|
| 187 |
- name: Sending an e-mail using Legacy SSL to the remote machine |
| 188 |
community.general.mail: |
| 189 |
host: localhost |
| 190 |
port: 25 |
| 191 |
to: John Smith <[email protected]> |
| 192 |
subject: Ansible-report |
| 193 |
body: System {{ ansible_hostname }} has been successfully provisioned. |
| 194 |
secure: always |
| 195 |
|
| 196 |
- name: Sending an e-mail using StartTLS to the remote machine |
| 197 |
community.general.mail: |
| 198 |
host: localhost |
| 199 |
port: 25 |
| 200 |
to: John Smith <[email protected]> |
| 201 |
subject: Ansible-report |
| 202 |
body: System {{ ansible_hostname }} has been successfully provisioned. |
| 203 |
secure: starttls |
| 204 |
|
| 205 |
- name: Sending an e-mail using StartTLS, remote server, custom EHLO, and timeout of 10 seconds |
| 206 |
community.general.mail: |
| 207 |
host: some.smtp.host.tld |
| 208 |
port: 25 |
| 209 |
timeout: 10 |
| 210 |
ehlohost: my-resolvable-hostname.tld |
| 211 |
to: John Smith <[email protected]> |
| 212 |
subject: Ansible-report |
| 213 |
body: System {{ ansible_hostname }} has been successfully provisioned. |
| 214 |
secure: starttls |
| 215 |
""" |
| 216 |
|
| 217 |
import os |
| 218 |
import smtplib |
| 219 |
import ssl |
| 220 |
import traceback |
| 221 |
from email import encoders |
| 222 |
from email.header import Header |
| 223 |
from email.mime.base import MIMEBase |
| 224 |
from email.mime.multipart import MIMEMultipart |
| 225 |
from email.mime.text import MIMEText |
| 226 |
from email.utils import formataddr, formatdate, make_msgid, parseaddr |
| 227 |
|
| 228 |
from ansible.module_utils.basic import AnsibleModule |
| 229 |
from ansible.module_utils.common.text.converters import to_native |
| 230 |
|
| 231 |
|
| 232 |
def main(): |
| 233 |
module = AnsibleModule( |
| 234 |
argument_spec=dict( |
| 235 |
username=dict(type="str"), |
| 236 |
password=dict(type="str", no_log=True), |
| 237 |
host=dict(type="str", default="localhost"), |
| 238 |
port=dict(type="int", default=25), |
| 239 |
ehlohost=dict(type="str"), |
| 240 |
sender=dict(type="str", default="root", aliases=["from"]), |
| 241 |
to=dict(type="list", elements="str", default=["root"], aliases=["recipients"]), |
| 242 |
cc=dict(type="list", elements="str", default=[]), |
| 243 |
bcc=dict(type="list", elements="str", default=[]), |
| 244 |
subject=dict(type="str", required=True, aliases=["msg"]), |
| 245 |
body=dict(type="str"), |
| 246 |
attach=dict(type="list", elements="path", default=[]), |
| 247 |
headers=dict(type="list", elements="str", default=[]), |
| 248 |
charset=dict(type="str", default="utf-8"), |
| 249 |
subtype=dict(type="str", default="plain", choices=["html", "plain"]), |
| 250 |
secure=dict(type="str", default="try", choices=["always", "never", "starttls", "try"]), |
| 251 |
timeout=dict(type="int", default=20), |
| 252 |
message_id_domain=dict(type="str", default="ansible"), |
| 253 |
), |
| 254 |
required_together=[["password", "username"]], |
| 255 |
) |
| 256 |
|
| 257 |
username = module.params.get("username") |
| 258 |
password = module.params.get("password") |
| 259 |
host = module.params.get("host") |
| 260 |
port = module.params.get("port") |
| 261 |
local_hostname = module.params.get("ehlohost") |
| 262 |
sender = module.params.get("sender") |
| 263 |
recipients = module.params.get("to") |
| 264 |
copies = module.params.get("cc") |
| 265 |
blindcopies = module.params.get("bcc") |
| 266 |
subject = module.params.get("subject") |
| 267 |
body = module.params.get("body") |
| 268 |
attach_files = module.params.get("attach") |
| 269 |
headers = module.params.get("headers") |
| 270 |
charset = module.params.get("charset") |
| 271 |
subtype = module.params.get("subtype") |
| 272 |
secure = module.params.get("secure") |
| 273 |
timeout = module.params.get("timeout") |
| 274 |
message_id_domain = module.params["message_id_domain"] |
| 275 |
|
| 276 |
code = 0 |
| 277 |
secure_state = False |
| 278 |
sender_phrase, sender_addr = parseaddr(sender) |
| 279 |
|
| 280 |
if not body: |
| 281 |
body = subject |
| 282 |
|
| 283 |
try: |
| 284 |
if secure != "never": |
| 285 |
try: |
| 286 |
smtp = smtplib.SMTP_SSL(host=host, port=port, local_hostname=local_hostname, timeout=timeout) |
| 287 |
code, smtpmessage = smtp.connect(host, port) |
| 288 |
secure_state = True |
| 289 |
except ssl.SSLError as e: |
| 290 |
if secure == "always": |
| 291 |
module.fail_json( |
| 292 |
rc=1, |
| 293 |
msg=f"Unable to start an encrypted session to {host}:{port}: {e}", |
| 294 |
exception=traceback.format_exc(), |
| 295 |
) |
| 296 |
except Exception: |
| 297 |
pass |
| 298 |
|
| 299 |
if not secure_state: |
| 300 |
smtp = smtplib.SMTP(host=host, port=port, local_hostname=local_hostname, timeout=timeout) |
| 301 |
code, smtpmessage = smtp.connect(host, port) |
| 302 |
|
| 303 |
except smtplib.SMTPException as e: |
| 304 |
module.fail_json(rc=1, msg=f"Unable to Connect {host}:{port}: {e}", exception=traceback.format_exc()) |
| 305 |
|
| 306 |
try: |
| 307 |
smtp.ehlo() |
| 308 |
except smtplib.SMTPException as e: |
| 309 |
module.fail_json(rc=1, msg=f"Helo failed for host {host}:{port}: {e}", exception=traceback.format_exc()) |
| 310 |
|
| 311 |
if int(code) > 0: |
| 312 |
if not secure_state and secure in ("starttls", "try"): |
| 313 |
if smtp.has_extn("STARTTLS"): |
| 314 |
try: |
| 315 |
smtp.starttls() |
| 316 |
secure_state = True |
| 317 |
except smtplib.SMTPException as e: |
| 318 |
module.fail_json( |
| 319 |
rc=1, |
| 320 |
msg=f"Unable to start an encrypted session to {host}:{port}: {e}", |
| 321 |
exception=traceback.format_exc(), |
| 322 |
) |
| 323 |
try: |
| 324 |
smtp.ehlo() |
| 325 |
except smtplib.SMTPException as e: |
| 326 |
module.fail_json( |
| 327 |
rc=1, msg=f"Helo failed for host {host}:{port}: {e}", exception=traceback.format_exc() |
| 328 |
) |
| 329 |
else: |
| 330 |
if secure == "starttls": |
| 331 |
module.fail_json(rc=1, msg=f"StartTLS is not offered on server {host}:{port}") |
| 332 |
|
| 333 |
if username and password: |
| 334 |
if smtp.has_extn("AUTH"): |
| 335 |
try: |
| 336 |
smtp.login(username, password) |
| 337 |
except smtplib.SMTPAuthenticationError: |
| 338 |
module.fail_json( |
| 339 |
rc=1, msg=f"Authentication to {host}:{port} failed, please check your username and/or password" |
| 340 |
) |
| 341 |
except smtplib.SMTPException: |
| 342 |
module.fail_json(rc=1, msg=f"No Suitable authentication method was found on {host}:{port}") |
| 343 |
else: |
| 344 |
module.fail_json(rc=1, msg=f"No Authentication on the server at {host}:{port}") |
| 345 |
|
| 346 |
if not secure_state and (username and password): |
| 347 |
module.warn("Username and Password was sent without encryption") |
| 348 |
|
| 349 |
msg = MIMEMultipart(_charset=charset) |
| 350 |
msg["From"] = formataddr((sender_phrase, sender_addr)) |
| 351 |
msg["Date"] = formatdate(localtime=True) |
| 352 |
msg["Subject"] = Header(subject, charset) |
| 353 |
msg["Message-ID"] = make_msgid(domain=message_id_domain) |
| 354 |
msg.preamble = "Multipart message" |
| 355 |
|
| 356 |
for header in headers: |
| 357 |
# NOTE: Backward compatible with old syntax using '|' as delimiter |
| 358 |
for hdr in [x.strip() for x in header.split("|")]: |
| 359 |
try: |
| 360 |
h_key, h_val = hdr.split("=", 1) |
| 361 |
h_val = to_native(Header(h_val, charset)) # TODO: use str() instead? |
| 362 |
msg.add_header(h_key, h_val) |
| 363 |
except Exception: |
| 364 |
module.warn(f"Skipping header '{hdr}', unable to parse") |
| 365 |
|
| 366 |
if "X-Mailer" not in msg: |
| 367 |
msg.add_header("X-Mailer", "Ansible mail module") |
| 368 |
|
| 369 |
addr_list = [] |
| 370 |
for addr in [x.strip() for x in blindcopies]: |
| 371 |
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase |
| 372 |
|
| 373 |
to_list = [] |
| 374 |
for addr in [x.strip() for x in recipients]: |
| 375 |
to_list.append(formataddr(parseaddr(addr))) |
| 376 |
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase |
| 377 |
msg["To"] = ", ".join(to_list) |
| 378 |
|
| 379 |
cc_list = [] |
| 380 |
for addr in [x.strip() for x in copies]: |
| 381 |
cc_list.append(formataddr(parseaddr(addr))) |
| 382 |
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase |
| 383 |
msg["Cc"] = ", ".join(cc_list) |
| 384 |
|
| 385 |
part = MIMEText(f"{body}\n\n", _subtype=subtype, _charset=charset) |
| 386 |
msg.attach(part) |
| 387 |
|
| 388 |
# NOTE: Backward compatibility with old syntax using space as delimiter is not retained |
| 389 |
# This breaks files with spaces in it :-( |
| 390 |
for filename in attach_files: |
| 391 |
try: |
| 392 |
part = MIMEBase("application", "octet-stream") |
| 393 |
with open(filename, "rb") as fp: |
| 394 |
part.set_payload(fp.read()) |
| 395 |
encoders.encode_base64(part) |
| 396 |
part.add_header("Content-disposition", "attachment", filename=os.path.basename(filename)) |
| 397 |
msg.attach(part) |
| 398 |
except Exception as e: |
| 399 |
module.fail_json( |
| 400 |
rc=1, |
| 401 |
msg=f"Failed to send community.general.mail: can't attach file {filename}: {e}", |
| 402 |
exception=traceback.format_exc(), |
| 403 |
) |
| 404 |
|
| 405 |
composed = msg.as_string() |
| 406 |
|
| 407 |
try: |
| 408 |
result = smtp.sendmail(sender_addr, set(addr_list), composed) |
| 409 |
except Exception as e: |
| 410 |
module.fail_json( |
| 411 |
rc=1, msg=f"Failed to send mail to '{', '.join(set(addr_list))}': {e}", exception=traceback.format_exc() |
| 412 |
) |
| 413 |
|
| 414 |
smtp.quit() |
| 415 |
|
| 416 |
if result: |
| 417 |
for key in result: |
| 418 |
module.warn(f"Failed to send mail to '{key}': {result[key][0]} {result[key][1]}") |
| 419 |
module.exit_json(msg="Failed to send mail to at least one recipient", result=result) |
| 420 |
|
| 421 |
module.exit_json(msg="Mail sent successfully", result=result) |
| 422 |
|
| 423 |
|
| 424 |
if __name__ == "__main__": |
| 425 |
main() |