Skip to content

Instantly share code, notes, and snippets.

@jabbalaci
Created June 15, 2016 10:00
Show Gist options
  • Save jabbalaci/003b0ab36b01e47dce136347bcba5359 to your computer and use it in GitHub Desktop.
Save jabbalaci/003b0ab36b01e47dce136347bcba5359 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# coding: utf8
"""
A simple wrapper for the `mailx` command.
Purpose
-------
Send an email notification to yourself from a Python script.
Configuration steps to make `mailx` work
----------------------------------------
* https://github.com/jabbalaci/DigitalOceanNotes#send-email-from-the-terminal-optional
Related blog post
-----------------
* https://ubuntuincident.wordpress.com/2016/06/15/email-notification-from-a-script/
Author
------
Jabba Laci, 2016, [email protected]
"""
import os
DEBUG = True
# DEBUG = False
class NoSubjectError(Exception):
pass
class NoRecipientError(Exception):
pass
def send_email(to='', subject='', body=''):
if not subject:
raise NoSubjectError
if not to:
raise NoRecipientError
#
if not body:
cmd = """mailx -s "{s}" < /dev/null "{to}" 2>/dev/null""".format(
s=subject, to=to
)
else:
cmd = """echo "{b}" | mailx -s "{s}" "{to}" 2>/dev/null""".format(
b=body, s=subject, to=to
)
if DEBUG:
print("#", cmd)
#
os.system(cmd)
def main():
send_email(to="[email protected]",
subject="subject")
#
send_email(to="[email protected]",
subject="subject",
body='this is the body of the email')
#############################################################################
if __name__ == "__main__":
main()
@rohitsingh2410
Copy link

how to make an attachment it it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment