Skip to content

Instantly share code, notes, and snippets.

@jabbalaci jabbalaci/email.py
Created Jun 15, 2016

Embed
What would you like to do?
#!/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, jabba.laci@gmail.com
"""
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="to@email.com",
subject="subject")
#
send_email(to="to@email.com",
subject="subject",
body='this is the body of the email')
#############################################################################
if __name__ == "__main__":
main()
@rohitsingh2410

This comment has been minimized.

Copy link

rohitsingh2410 commented Jan 30, 2018

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
You can’t perform that action at this time.