Examples — Python 3.11.0 documentation (2023)

Here are a few examples of how to use the email package to read, write,and send simple email messages, as well as more complex MIME messages.

First, let’s see how to create and send a simple text message (both thetext content and the addresses may contain unicode characters):

# Import smtplib for the actual sending functionimport smtplib# Import the email modules we'll needfrom email.message import EmailMessage# Open the plain text file whose name is in textfile for reading.with open(textfile) as fp: # Create a text/plain message msg = EmailMessage() msg.set_content(fp.read())# me == the sender's email address# you == the recipient's email addressmsg['Subject'] = f'The contents of {textfile}'msg['From'] = memsg['To'] = you# Send the message via our own SMTP server.s = smtplib.SMTP('localhost')s.send_message(msg)s.quit()
(Video) NEW Python 3.11 !!!

Parsing RFC 822 headers can easily be done by the using the classesfrom the parser module:

# Import the email modules we'll needfrom email.parser import BytesParser, Parserfrom email.policy import default# If the e-mail headers are in a file, uncomment these two lines:# with open(messagefile, 'rb') as fp:# headers = BytesParser(policy=default).parse(fp)# Or for parsing headers in a string (this is an uncommon operation), use:headers = Parser(policy=default).parsestr( 'From: Foo Bar <user@example.com>\n' 'To: <someone_else@example.com>\n' 'Subject: Test message\n' '\n' 'Body would go here\n')# Now the header items can be accessed as a dictionary:print('To: {}'.format(headers['to']))print('From: {}'.format(headers['from']))print('Subject: {}'.format(headers['subject']))# You can also access the parts of the addresses:print('Recipient username: {}'.format(headers['to'].addresses[0].username))print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

Here’s an example of how to send a MIME message containing a bunch of familypictures that may be residing in a directory:

# Import smtplib for the actual sending function.import smtplib# Here are the email package modules we'll need.from email.message import EmailMessage# Create the container email message.msg = EmailMessage()msg['Subject'] = 'Our family reunion'# me == the sender's email address# family = the list of all recipients' email addressesmsg['From'] = memsg['To'] = ', '.join(family)msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'# Open the files in binary mode. You can also omit the subtype# if you want MIMEImage to guess it.for file in pngfiles: with open(file, 'rb') as fp: img_data = fp.read() msg.add_attachment(img_data, maintype='image', subtype='png')# Send the email via our own SMTP server.with smtplib.SMTP('localhost') as s: s.send_message(msg)
(Video) It's time... for PYTHON 3.11!

Here’s an example of how to send the entire contents of a directory as an emailmessage: 1

#!/usr/bin/env python3"""Send the contents of a directory as a MIME message."""import osimport smtplib# For guessing MIME type based on file name extensionimport mimetypesfrom argparse import ArgumentParserfrom email.message import EmailMessagefrom email.policy import SMTPdef main(): parser = ArgumentParser(description="""\Send the contents of a directory as a MIME message.Unless the -o option is given, the email is sent by forwarding to your localSMTP server, which then does the normal delivery process. Your local machinemust be running an SMTP server.""") parser.add_argument('-d', '--directory', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_argument('-o', '--output', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_argument('-s', '--sender', required=True, help='The value of the From: header (required)') parser.add_argument('-r', '--recipient', required=True, action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') args = parser.parse_args() directory = args.directory if not directory: directory = '.' # Create the message msg = EmailMessage() msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}' msg['To'] = ', '.join(args.recipients) msg['From'] = args.sender msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) # Now send or store the message if args.output: with open(args.output, 'wb') as fp: fp.write(msg.as_bytes(policy=SMTP)) else: with smtplib.SMTP('localhost') as s: s.send_message(msg)if __name__ == '__main__': main()

Here’s an example of how to unpack a MIME message like the oneabove, into a directory of files:

#!/usr/bin/env python3"""Unpack a MIME message into a directory of files."""import osimport emailimport mimetypesfrom email.policy import defaultfrom argparse import ArgumentParserdef main(): parser = ArgumentParser(description="""\Unpack a MIME message into a directory of files.""") parser.add_argument('-d', '--directory', required=True, help="""Unpack the MIME message into the named directory, which will be created if it doesn't already exist.""") parser.add_argument('msgfile') args = parser.parse_args() with open(args.msgfile, 'rb') as fp: msg = email.message_from_binary_file(fp, policy=default) try: os.mkdir(args.directory) except FileExistsError: pass counter = 1 for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = f'part-{counter:03d}{ext}' counter += 1 with open(os.path.join(args.directory, filename), 'wb') as fp: fp.write(part.get_payload(decode=True))if __name__ == '__main__': main()
(Video) You Are Going To Like These New Features In Python 3.11

Here’s an example of how to create an HTML message with an alternative plaintext version. To make things a bit more interesting, we include a relatedimage in the html part, and we save a copy of what we are going to send todisk, as well as sending it.

#!/usr/bin/env python3import smtplibfrom email.message import EmailMessagefrom email.headerregistry import Addressfrom email.utils import make_msgid# Create the base text message.msg = EmailMessage()msg['Subject'] = "Ayons asperges pour le déjeuner"msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"), Address("Fabrette Pussycat", "fabrette", "example.com"))msg.set_content("""\Salut!Cela ressemble à un excellent recipie[1] déjeuner.[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718--Pepé""")# Add the html version. This converts the message into a multipart/alternative# container, with the original text message as the first part and the new html# message as the second part.asparagus_cid = make_msgid()msg.add_alternative("""\<html> <head></head> <body> <p>Salut!</p> <p>Cela ressemble à un excellent <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718"> recipie </a> déjeuner. </p> <img src="cid:{asparagus_cid}" /> </body></html>""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')# note that we needed to peel the <> off the msgid for use in the html.# Now add the related image to the html part.with open("roasted-asparagus.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid)# Make a local copy of what we are going to send.with open('outgoing.msg', 'wb') as f: f.write(bytes(msg))# Send the message via local SMTP server.with smtplib.SMTP('localhost') as s: s.send_message(msg)

If we were sent the message from the last example, here is one way we couldprocess it:

import osimport sysimport tempfileimport mimetypesimport webbrowser# Import the email modules we'll needfrom email import policyfrom email.parser import BytesParserdef magic_html_parser(html_text, partfiles): """Return safety-sanitized html linked to partfiles. Rewrite the href="cid:...." attributes to point to the filenames in partfiles. Though not trivial, this should be possible using html.parser. """ raise NotImplementedError("Add the magic needed")# In a real program you'd get the filename from the arguments.with open('outgoing.msg', 'rb') as fp: msg = BytesParser(policy=policy.default).parse(fp)# Now the header items can be accessed as a dictionary, and any non-ASCII will# be converted to unicode:print('To:', msg['to'])print('From:', msg['from'])print('Subject:', msg['subject'])# If we want to print a preview of the message content, we can extract whatever# the least formatted payload is and print the first three lines. Of course,# if the message has no plain text part printing the first three lines of html# is probably useless, but this is just a conceptual example.simplest = msg.get_body(preferencelist=('plain', 'html'))print()print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))ans = input("View full message?")if ans.lower()[0] == 'n': sys.exit()# We can extract the richest alternative in order to display it:richest = msg.get_body()partfiles = {}if richest['content-type'].maintype == 'text': if richest['content-type'].subtype == 'plain': for line in richest.get_content().splitlines(): print(line) sys.exit() elif richest['content-type'].subtype == 'html': body = richest else: print("Don't know how to display {}".format(richest.get_content_type())) sys.exit()elif richest['content-type'].content_type == 'multipart/related': body = richest.get_body(preferencelist=('html')) for part in richest.iter_attachments(): fn = part.get_filename() if fn: extension = os.path.splitext(part.get_filename())[1] else: extension = mimetypes.guess_extension(part.get_content_type()) with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f: f.write(part.get_content()) # again strip the <> to go from email form of cid to html form. partfiles[part['content-id'][1:-1]] = f.nameelse: print("Don't know how to display {}".format(richest.get_content_type())) sys.exit()with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: f.write(magic_html_parser(body.get_content(), partfiles))webbrowser.open(f.name)os.remove(f.name)for fn in partfiles.values(): os.remove(fn)# Of course, there are lots of email messages that could break this simple# minded program, but it will handle the most common ones.
(Video) Python 3.11 is out! All new features

Up to the prompt, the output from the above is:

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>From: Pepé Le Pew <pepe@example.com>Subject: Ayons asperges pour le déjeunerSalut!Cela ressemble à un excellent recipie[1] déjeuner.

Footnotes

1

Thanks to Matthew Dixon Cowles for the original inspiration and examples.

FAQs

Can you download Python documentation? ›

Browse the docs online or download a copy of your own.

Python's documentation, tutorials, and guides are constantly evolving. Get started here, or scroll down for documentation broken out by type and subject.

Which is the best documentation for Python? ›

Sphinx is far and away the most popular Python documentation tool. Use it. It converts reStructuredText markup language into a range of output formats including HTML, LaTeX (for printable PDF versions), manual pages, and plain text. There is also great, free hosting for your Sphinx docs: Read The Docs.

What does __ doc __ mean in Python? ›

The __doc__ attribute

Each Python object (functions, classes, variables,...) provides (if programmer has filled it) a short documentation which describes its features. You can access it with commands like print myobject.

What is documentation of project with example? ›

Project documentation is the implementation of a streamlined, efficient, and uniform process for producing the key documents that are required to implement a new project successfully. For example, these documents might include, business cases, project status reports, and project requirement sheets.

How do I make my own documentation? ›

How to Write Project Documentation in 5 Easy Steps
  1. Step 1: Bring all Scattered Documents in One Place. ...
  2. Step 2: Take it Stage by Stage. ...
  3. Step 3: Structure the Document & Make it Easy to Search. ...
  4. Step 4: Let Your Team Review the Document Before Sharing. ...
  5. Step 5: Maintain the Document's Relevance.
20 Feb 2022

How do you write documentation for a project? ›

Best Practices for Documenting Your Project
  1. Include a README file that contains. ...
  2. Allow issue tracker for others.
  3. Write an API documentation. ...
  4. Document your code.
  5. Apply coding conventions, such as file organization, comments, naming conventions, programming practices, etc.
  6. Include information for contributors.
29 Jun 2022

How do I get Python documents offline? ›

Below are presented 3 methods to view Python documentation offline ( without internet connection ), while having already python installed on the system.
  1. Using the installed python documentation on Windows. ...
  2. Using command line pydoc script at CMD / Terminal. ...
  3. Using the python interpretor - help function.

Is Python docs good for beginners? ›

Python is an easy to learn, powerful programming language.

Is it worth reading the Python documentation? ›

You should also be able to explain what your code is doing at a glance. Read the documentation and any supporting material you find helpful to learn the basics, and then read it as necessary when learning new modules and libraries. I learn best by doing, and after a certain point I think reading is a waste of time.

Is 2 months enough for Python? ›

In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.

Why is Python faster than Excel? ›

Python for data analysis

It can easily replace mundane tasks with automation. Python also offers greater efficiency and scalability. It's faster than Excel for data pipelines, automation and calculating complex equations and algorithms.

What is the best tool for documentation? ›

The best software documentation tools for your team
  • Scribe.
  • Nuclino.
  • ProProfs Knowledge Base.
  • Notion.
  • Document360.
  • Confluence.
  • GitBook.
  • Bit.ai.

What are the examples of documentation? ›

Examples are user guides, white papers, online help, and quick-reference guides. Paper or hard-copy documentation has become less common. Documentation is often distributed via websites, software products, and other online applications.

What are the 4 types of documentation? ›

The four kinds of documentation are:
  • learning-oriented tutorials.
  • goal-oriented how-to guides.
  • understanding-oriented discussions.
  • information-oriented reference material.

What are the steps of documentation? ›

How to create a process document
  1. Scope the initial process. ...
  2. Define process boundaries. ...
  3. Determine process inputs and outputs. ...
  4. Identify process steps. ...
  5. Connect with project stakeholders. ...
  6. Construct a process flowchart. ...
  7. Note process flow exceptions. ...
  8. Test the process.
19 Aug 2021

What is print (__ doc __)? ›

""" The print(__doc__) command simply re-uses that documentation string to write it to your terminal each time you run the script, and any other python tool (like the interactive interpreter help() function, for example) can introspect that same value.

Should __ init __ have a docstring? ›

Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory. String literals occurring elsewhere in Python code may also act as documentation.

What is docstring and Doctest? ›

Docstrings in Python are used not only for the description of a class or a function to provide a better understanding of the code and use but, also used for Testing purposes. The Doctest Module finds patterns in the docstring that looks like interactive shell commands.

What are the five common types of documentation? ›

Types of Documentation

Types of system documentation include a requirements document, source code document, quality assurance documentation, software architecture documentation, solution instructions and a help guide for advanced users.

What are examples of good documentation practices? ›

Good Documentation Practice Standards
  • Analytical methods.
  • Batch manufacturing record forms.
  • Bills of materials (BOMs)
  • Calibration records.
  • Certificate of Analysis (CoA)
  • Certificate of Compliance (CoC)
  • Checklists.
10 Feb 2022

What is basic documentation? ›

Basic Document means this Agreement, the Loan Documents and all other documents and certificates contemplated thereby or delivered in connection therewith. Basic Document means the Note and this Agreement.

What are the 3 rules of documentation? ›

Documentation should be:
  • Immediate. Managers should take notes right after an incident occurs. ...
  • Accurate and believable. When an outside observer (judge, jury or EEO investigator) is called to judge your side of the story, detailed observations add authenticity. ...
  • Agreed upon.
16 Jul 2015

What is a documentation template? ›

A document template is a blueprint for generating documents. The template defines what data is to be extracted from the data source and how this data is formatted in the output. Document templates are self-contained archive files with the extension . dta (Document Template Archive).

What are the two types of documentation? ›

The two most common types of documentation used in research are note citations and parenthetical citations (Winkler & McCuen-Metherell, 2008, p. 4).

Can you run Python without internet? ›

Install Python on the offline computer. Install the Python package installer on the offline computer. On the offline computer, install the odbc cli database driver. On the offline computer, export the database home parameter.

Where is Python documentation stored? ›

Look in the python folder in the folder: Doc . This folder has the entire downloaded documentation of the python docs from python.org.

Which is the best offline Python compiler? ›

Most Popular Python Compilers
  • Programiz.
  • PyDev.
  • PyCharm.
  • Sublime Text.
  • Thonny.
  • Visual Studio Code.
  • Jupyter Notebook.
  • Vim.
25 Oct 2022

Is 50 too old to learn Python? ›

Also, they sometimes find silly excuses not to do something. Are you still asking yourself: “Is it too late to learn programming?” The answer is no. It's actually the best time to start! But, if you need some more convincing, let's look at a few different age groups and their advantages.

Can I learn Python in 4 days? ›

A beginner will take about 6-8 weeks to learn the fundamentals of Python. It takes that much time to learn how to understand most lines of code in Python. It would take significantly more time learning Python to move into a new career as a Python Developer.

Do hackers need to learn Python? ›

Python is a must-know programming language for anyone seeking a career in penetration testing.

Is Python certificate sufficient to get a job? ›

Even the most popular software development companies in India don't have the required resources that are skilled in python. While the language is gaining popularity, there is still not enough interest in pursuing a course or certification in acquiring this skill to start a career.

Is reading documentation a skill? ›

Reading documentation is a skill that is going to make your life easier as a developer. It is going to help you as much as writing documentation. Zeal (or Dash in the case of Mac) may come in handy in hosting documentation for some of your commonly used languages.

What should you not use Python for? ›

Not suitable for Mobile and Game Development

Python is mostly used in desktop and web server-side development. It is not considered ideal for mobile app development and game development due to the consumption of more memory and its slow processing speed while compared to other programming languages.

Can I learn Python by reading the documentation? ›

Official Python Documentation

You do not have to read all of the documentation. In fact, that's not an efficient way to learn Python programming. However, you should use it freely as reference and get familiar with it so you can easily find what you are looking for.

How do I access Python help documents? ›

Python help() function docstring

All functions should have a docstring. Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.

Can I learn Python in a month? ›

In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.

Is Python certification hard? ›

While Python is considered one of the easiest programming languages for a beginner to learn, it can be hard to master. Anyone can learn Python if they work hard enough at it, but becoming a Python Developer will require a lot of practice and patience.

Will there be a Python 4? ›

Python 4.0 will probably never come — according to the creator of Python, Guido van Rossum. The lessons learned from migrating from Python 2 to Python 3 demonstrated what a hassle it is to move to a new language version. Thus, there will probably not be a new version of Python soon.

Is Python easy to crack? ›

Because Python is similar to English, many find it easier to learn than other programming languages. Developers can read and remember the Python syntaxes much easier than other programming languages.

Is Python or C++ better for beginners? ›

Python leads to one conclusion: Python is better for beginners in terms of its easy-to-read code and simple syntax. Additionally, Python is a good option for web development (backend), while C++ is not very popular in web development of any kind. Python is also a leading language for data analysis and machine learning.

Can a 9 year old learn Python? ›

With the increased utilisation of digital devices, Python is an important skill that you can teach your children. This computer language is easy for children as young as 10 years old to understand.

Where can I practice problems of Python? ›

Where can I practice Python programming? Dataquest.io has dozens of free interactive practice questions, as well as free interactive lessons, project ideas, tutorials, and more. HackerRank is a great site for practice that's also interactive. CodingGame is a fun platform for practice that supports Python.

How do you write code in Python? ›

The Easiest Way to Run Python
  1. Download Thonny IDE.
  2. Run the installer to install Thonny on your computer.
  3. Go to: File > New. Then save the file with .py extension. ...
  4. Write Python code in the file and save it. Running Python using Thonny IDE.
  5. Then Go to Run > Run current script or simply click F5 to run it.

Videos

1. How to Install Python 3.11.0 on Windows 7, 10 or 11 (64-bit) and Run Python Code In VSCode
(Semicolon Dot Dev)
2. How to install Python 3.11.0 on Windows 10
(Amit Thinks)
3. How to Install Python 3.11.0 on Windows 10/11 [ 2022 Update ] Complete Guide
(Geeky Script)
4. How To Use The NEW "Self" Type In Python 3.11 (NEW FEATURE!)
(Indently)
5. Your guide to Python 3.11
(Carberra)
6. What's new in Python 3.11?
(Doug Mercer)
Top Articles
Latest Posts
Article information

Author: Lidia Grady

Last Updated: 02/23/2023

Views: 6353

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.