Skip to content

Instantly share code, notes, and snippets.

@kylegibson
Created October 28, 2010 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylegibson/650783 to your computer and use it in GitHub Desktop.
Save kylegibson/650783 to your computer and use it in GitHub Desktop.
Python Generate Email with Attachment
#!/usr/bin/python
# ./generate_email_with_attachment.py files.tar.bz2 user_to@domain.com > email_output
from email.encoders import encode_base64
from email.mime import Base, Multipart
from mimetypes import guess_type
def main(args):
file_path = args[1]
to = args[2]
ctype, encoding = guess_type(file_path)
outer = Multipart.MIMEMultipart()
outer["Subject"] = "See attached file %s" % file_path
outer["To"] = to
outer.preamble = "File is attached"
maintype, subtype = ctype.split("/")
msg = Base.MIMEBase(maintype, subtype)
fp = open(file_path, "r")
msg.set_payload(fp.read())
fp.close()
encode_base64(msg)
msg.add_header("Content-Disposition", "attachment", filename=file_path)
outer.attach(msg)
print outer.as_string()
if __name__ == "__main__":
import sys
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment