parthtamu/rag-code-assistant
0
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="email.generator: Generating MIME documents" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/email.generator.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/email/generator.py One of the most common tasks is to generate the flat (serialized) version of the email message represented by a message object structure. You will need to do thi..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_email.generator_bcf9521e.png" />15<meta property="og:image:alt" content="Source code: Lib/email/generator.py One of the most common tasks is to generate the flat (serialized) version of the email message represented by a message object structure. You will need to do thi..." />16<meta name="description" content="Source code: Lib/email/generator.py One of the most common tasks is to generate the flat (serialized) version of the email message represented by a message object structure. You will need to do thi..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20 <title>email.generator: Generating MIME documents — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21 22 <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23 <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24 <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25 <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26 <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27 28 <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29 <script src="../_static/doctools.js?v=9bcbadda"></script>30 <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31 <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32 33 <script src="../_static/sidebar.js"></script>34 35 <link rel="search" type="application/opensearchdescription+xml"36 title="Search within Python 3.15.0a6 documentation"37 href="../_static/opensearch.xml"/>38 <link rel="author" title="About these documents" href="../about.html" />39 <link rel="index" title="Index" href="../genindex.html" />40 <link rel="search" title="Search" href="../search.html" />41 <link rel="copyright" title="Copyright" href="../copyright.html" />42 <link rel="next" title="email.policy: Policy Objects" href="email.policy.html" />43 <link rel="prev" title="email.parser: Parsing email messages" href="email.parser.html" />44 45 46 <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47 48 <link rel="canonical" href="https://docs.python.org/3/library/email.generator.html">49 50 51 52 53 <style>54 @media only screen {55 table.full-width-table {56 width: 100%;57 }58 }59 </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61 <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62 <script type="text/javascript" src="../_static/copybutton.js"></script>63 <script type="text/javascript" src="../_static/menu.js"></script>64 <script type="text/javascript" src="../_static/search-focus.js"></script>65 <script type="text/javascript" src="../_static/themetoggle.js"></script> 66 <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67 <meta name="readthedocs-addons-api-version" content="1">68 69 </head>70<body>71<div class="mobile-nav">72 <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73 aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74 <nav class="nav-content" role="navigation">75 <label for="menuToggler" class="toggler__label">76 <span></span>77 </label>78 <span class="nav-items-wrapper">79 <a href="https://www.python.org/" class="nav-logo">80 <img src="../_static/py.svg" alt="Python logo">81 </a>82 <span class="version_switcher_placeholder"></span>83 <form role="search" class="search" action="../search.html" method="get">84 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85 <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86 </svg>87 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88 <input type="submit" value="Go">89 </form>90 </span>91 </nav>92 <div class="menu-wrapper">93 <nav class="menu" role="navigation" aria-label="main navigation">94 <div class="language_switcher_placeholder"></div>95 96<label class="theme-selector-label">97 Theme98 <select class="theme-selector" oninput="activateTheme(this.value)">99 <option value="auto" selected>Auto</option>100 <option value="light">Light</option>101 <option value="dark">Dark</option>102 </select>103</label>104 <div>105 <h4>Previous topic</h4>106 <p class="topless"><a href="email.parser.html"107 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a></p>108 </div>109 <div>110 <h4>Next topic</h4>111 <p class="topless"><a href="email.policy.html"112 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.policy</span></code>: Policy Objects</a></p>113 </div>114 <script>115 document.addEventListener('DOMContentLoaded', () => {116 const title = document.querySelector('meta[property="og:title"]').content;117 const elements = document.querySelectorAll('.improvepage');118 const pageurl = window.location.href.split('?')[0];119 elements.forEach(element => {120 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));121 url.searchParams.set('pagetitle', title);122 url.searchParams.set('pageurl', pageurl);123 url.searchParams.set('pagesource', "library/email.generator.rst");124 element.href = url.toString();125 });126 });127 </script>128 <div role="note" aria-label="source link">129 <h3>This page</h3>130 <ul class="this-page-menu">131 <li><a href="../bugs.html">Report a bug</a></li>132 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>133 <li>134 <a href="https://github.com/python/cpython/blob/main/Doc/library/email.generator.rst?plain=1"135 rel="nofollow">Show source136 </a>137 </li>138 139 </ul>140 </div>141 </nav>142 </div>143</div>144 145 146 <div class="related" role="navigation" aria-label="Related">147 <h3>Navigation</h3>148 <ul>149 <li class="right" style="margin-right: 10px">150 <a href="../genindex.html" title="General Index"151 accesskey="I">index</a></li>152 <li class="right" >153 <a href="../py-modindex.html" title="Python Module Index"154 >modules</a> |</li>155 <li class="right" >156 <a href="email.policy.html" title="email.policy: Policy Objects"157 accesskey="N">next</a> |</li>158 <li class="right" >159 <a href="email.parser.html" title="email.parser: Parsing email messages"160 accesskey="P">previous</a> |</li>161 162 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>163 <li><a href="https://www.python.org/">Python</a> »</li>164 <li class="switchers">165 <div class="language_switcher_placeholder"></div>166 <div class="version_switcher_placeholder"></div>167 </li>168 <li>169 170 </li>171 <li id="cpython-language-and-version">172 <a href="../index.html">3.15.0a6 Documentation</a> »173 </li>174 175 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>176 <li class="nav-item nav-item-2"><a href="netdata.html" >Internet Data Handling</a> »</li>177 <li class="nav-item nav-item-3"><a href="email.html" accesskey="U"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> »</li>178 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></li>179 <li class="right">180 181 182 <div class="inline-search" role="search">183 <form class="inline-search" action="../search.html" method="get">184 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">185 <input type="submit" value="Go">186 </form>187 </div>188 |189 </li>190 <li class="right">191<label class="theme-selector-label">192 Theme193 <select class="theme-selector" oninput="activateTheme(this.value)">194 <option value="auto" selected>Auto</option>195 <option value="light">Light</option>196 <option value="dark">Dark</option>197 </select>198</label> |</li>199 200 </ul>201 </div> 202 203 <div class="document">204 <div class="documentwrapper">205 <div class="bodywrapper">206 <div class="body" role="main">207 208 <section id="module-email.generator">209<span id="email-generator-generating-mime-documents"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents<a class="headerlink" href="#module-email.generator" title="Link to this heading">¶</a></h1>210<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/email/generator.py">Lib/email/generator.py</a></p>211<hr class="docutils" />212<p>One of the most common tasks is to generate the flat (serialized) version of213the email message represented by a message object structure. You will need to214do this if you want to send your message via <a class="reference internal" href="smtplib.html#smtplib.SMTP.sendmail" title="smtplib.SMTP.sendmail"><code class="xref py py-meth docutils literal notranslate"><span class="pre">smtplib.SMTP.sendmail()</span></code></a>,215or print the message on the console. Taking a216message object structure and producing a serialized representation is the job217of the generator classes.</p>218<p>As with the <a class="reference internal" href="email.parser.html#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a> module, you aren’t limited to the functionality219of the bundled generator; you could write one from scratch yourself. However220the bundled generator knows how to generate most email in a standards-compliant221way, should handle MIME and non-MIME email messages just fine, and is designed222so that the bytes-oriented parsing and generation operations are inverses,223assuming the same non-transforming <a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">policy</span></code></a> is used for both. That224is, parsing the serialized byte stream via the225<a class="reference internal" href="email.parser.html#email.parser.BytesParser" title="email.parser.BytesParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesParser</span></code></a> class and then regenerating the serialized226byte stream using <a class="reference internal" href="#email.generator.BytesGenerator" title="email.generator.BytesGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code></a> should produce output identical to227the input <a class="footnote-reference brackets" href="#id3" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>. (On the other hand, using the generator on an228<a class="reference internal" href="email.message.html#email.message.EmailMessage" title="email.message.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a> constructed by program may result in229changes to the <code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code> object as defaults are230filled in.)</p>231<p>The <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class can be used to flatten a message into a text (as232opposed to binary) serialized representation, but since Unicode cannot233represent binary data directly, the message is of necessity transformed into234something that contains only ASCII characters, using the standard email RFC235Content Transfer Encoding techniques for encoding email messages for transport236over channels that are not “8 bit clean”.</p>237<p>To accommodate reproducible processing of SMIME-signed messages238<a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> disables header folding for message parts of type239<code class="docutils literal notranslate"><span class="pre">multipart/signed</span></code> and all subparts.</p>240<dl class="py class">241<dt class="sig sig-object py" id="email.generator.BytesGenerator">242<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">email.generator.</span></span><span class="sig-name descname"><span class="pre">BytesGenerator</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">outfp</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">mangle_from_</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">maxheaderlen</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">policy</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.BytesGenerator" title="Link to this definition">¶</a></dt>243<dd><p>Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code> object that will write any message provided244to the <a class="reference internal" href="#email.generator.BytesGenerator.flatten" title="email.generator.BytesGenerator.flatten"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flatten()</span></code></a> method, or any surrogateescape encoded text provided245to the <a class="reference internal" href="#email.generator.BytesGenerator.write" title="email.generator.BytesGenerator.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method, to the <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a> <em>outfp</em>.246<em>outfp</em> must support a <code class="docutils literal notranslate"><span class="pre">write</span></code> method that accepts binary data.</p>247<p>If optional <em>mangle_from_</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, put a <code class="docutils literal notranslate"><span class="pre">></span></code> character in front of248any line in the body that starts with the exact string <code class="docutils literal notranslate"><span class="pre">"From</span> <span class="pre">"</span></code>, that is249<code class="docutils literal notranslate"><span class="pre">From</span></code> followed by a space at the beginning of a line. <em>mangle_from_</em>250defaults to the value of the <a class="reference internal" href="email.policy.html#email.policy.Policy.mangle_from_" title="email.policy.Policy.mangle_from_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mangle_from_</span></code></a>251setting of the <em>policy</em> (which is <code class="docutils literal notranslate"><span class="pre">True</span></code> for the252<a class="reference internal" href="email.policy.html#email.policy.compat32" title="email.policy.compat32"><code class="xref py py-data docutils literal notranslate"><span class="pre">compat32</span></code></a> policy and <code class="docutils literal notranslate"><span class="pre">False</span></code> for all others).253<em>mangle_from_</em> is intended for use when messages are stored in Unix mbox254format (see <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> and <a class="reference external" href="https://www.jwz.org/doc/content-length.html">WHY THE CONTENT-LENGTH FORMAT IS BAD</a>).</p>255<p>If <em>maxheaderlen</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, refold any header lines that are longer256than <em>maxheaderlen</em>, or if <code class="docutils literal notranslate"><span class="pre">0</span></code>, do not rewrap any headers. If257<em>manheaderlen</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), wrap headers and other message258lines according to the <em>policy</em> settings.</p>259<p>If <em>policy</em> is specified, use that policy to control message generation. If260<em>policy</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), use the policy associated with the261<a class="reference internal" href="email.compat32-message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> or <a class="reference internal" href="email.message.html#email.message.EmailMessage" title="email.message.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a>262object passed to <code class="docutils literal notranslate"><span class="pre">flatten</span></code> to control the message generation. See263<a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.policy</span></code></a> for details on what <em>policy</em> controls.</p>264<div class="versionadded">265<p><span class="versionmodified added">Added in version 3.2.</span></p>266</div>267<div class="versionchanged">268<p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>policy</em> keyword.</p>269</div>270<div class="versionchanged">271<p><span class="versionmodified changed">Changed in version 3.6: </span>The default behavior of the <em>mangle_from_</em>272and <em>maxheaderlen</em> parameters is to follow the policy.</p>273</div>274<dl class="py method">275<dt class="sig sig-object py" id="email.generator.BytesGenerator.flatten">276<span class="sig-name descname"><span class="pre">flatten</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">msg</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">unixfrom</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">linesep</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.BytesGenerator.flatten" title="Link to this definition">¶</a></dt>277<dd><p>Print the textual representation of the message object structure rooted278at <em>msg</em> to the output file specified when the <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code>279instance was created.</p>280<p>If the <a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">policy</span></code></a> option <a class="reference internal" href="email.policy.html#email.policy.Policy.cte_type" title="email.policy.Policy.cte_type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">cte_type</span></code></a>281is <code class="docutils literal notranslate"><span class="pre">8bit</span></code> (the default), copy any headers in the original parsed282message that have not been modified to the output with any bytes with the283high bit set reproduced as in the original, and preserve the non-ASCII284<em class="mailheader">Content-Transfer-Encoding</em> of any body parts that have them.285If <code class="docutils literal notranslate"><span class="pre">cte_type</span></code> is <code class="docutils literal notranslate"><span class="pre">7bit</span></code>, convert the bytes with the high bit set as286needed using an ASCII-compatible <em class="mailheader">Content-Transfer-Encoding</em>.287That is, transform parts with non-ASCII288<em class="mailheader">Content-Transfer-Encoding</em>289(<em class="mailheader">Content-Transfer-Encoding: 8bit</em>) to an ASCII compatible290<em class="mailheader">Content-Transfer-Encoding</em>, and encode RFC-invalid non-ASCII291bytes in headers using the MIME <code class="docutils literal notranslate"><span class="pre">unknown-8bit</span></code> character set, thus292rendering them RFC-compliant.</p>293<p>If <em>unixfrom</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, print the envelope header delimiter used by294the Unix mailbox format (see <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a>) before the first of the295<span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5322.html"><strong>RFC 5322</strong></a> headers of the root message object. If the root object has296no envelope header, craft a standard one. The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>.297Note that for subparts, no envelope header is ever printed.</p>298<p>If <em>linesep</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, use it as the separator character between299all the lines of the flattened message. If <em>linesep</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the300default), use the value specified in the <em>policy</em>.</p>301</dd></dl>302 303<dl class="py method">304<dt class="sig sig-object py" id="email.generator.BytesGenerator.clone">305<span class="sig-name descname"><span class="pre">clone</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fp</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.BytesGenerator.clone" title="Link to this definition">¶</a></dt>306<dd><p>Return an independent clone of this <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code> instance with307the exact same option settings, and <em>fp</em> as the new <em>outfp</em>.</p>308</dd></dl>309 310<dl class="py method">311<dt class="sig sig-object py" id="email.generator.BytesGenerator.write">312<span class="sig-name descname"><span class="pre">write</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">s</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.BytesGenerator.write" title="Link to this definition">¶</a></dt>313<dd><p>Encode <em>s</em> using the <code class="docutils literal notranslate"><span class="pre">ASCII</span></code> codec and the <code class="docutils literal notranslate"><span class="pre">surrogateescape</span></code> error314handler, and pass it to the <em>write</em> method of the <em>outfp</em> passed to the315<code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code>’s constructor.</p>316</dd></dl>317 318</dd></dl>319 320<p>As a convenience, <a class="reference internal" href="email.message.html#email.message.EmailMessage" title="email.message.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a> provides the methods321<a class="reference internal" href="email.message.html#email.message.EmailMessage.as_bytes" title="email.message.EmailMessage.as_bytes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_bytes()</span></code></a> and <code class="docutils literal notranslate"><span class="pre">bytes(aMessage)</span></code> (a.k.a.322<a class="reference internal" href="email.message.html#email.message.EmailMessage.__bytes__" title="email.message.EmailMessage.__bytes__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bytes__()</span></code></a>), which simplify the generation of323a serialized binary representation of a message object. For more detail, see324<a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a>.</p>325<p>Because strings cannot represent binary data, the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class must326convert any binary data in any message it flattens to an ASCII compatible327format, by converting them to an ASCII compatible328<em class="mailheader">Content-Transfer_Encoding</em>. Using the terminology of the email329RFCs, you can think of this as <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code> serializing to an I/O stream330that is not “8 bit clean”. In other words, most applications will want331to be using <a class="reference internal" href="#email.generator.BytesGenerator" title="email.generator.BytesGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesGenerator</span></code></a>, and not <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code>.</p>332<dl class="py class">333<dt class="sig sig-object py" id="email.generator.Generator">334<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">email.generator.</span></span><span class="sig-name descname"><span class="pre">Generator</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">outfp</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">mangle_from_</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">maxheaderlen</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">policy</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator" title="Link to this definition">¶</a></dt>335<dd><p>Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code> object that will write any message provided336to the <a class="reference internal" href="#email.generator.Generator.flatten" title="email.generator.Generator.flatten"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flatten()</span></code></a> method, or any text provided to the <a class="reference internal" href="#email.generator.Generator.write" title="email.generator.Generator.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a>337method, to the <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a> <em>outfp</em>. <em>outfp</em> must support a338<code class="docutils literal notranslate"><span class="pre">write</span></code> method that accepts string data.</p>339<p>If optional <em>mangle_from_</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, put a <code class="docutils literal notranslate"><span class="pre">></span></code> character in front of340any line in the body that starts with the exact string <code class="docutils literal notranslate"><span class="pre">"From</span> <span class="pre">"</span></code>, that is341<code class="docutils literal notranslate"><span class="pre">From</span></code> followed by a space at the beginning of a line. <em>mangle_from_</em>342defaults to the value of the <a class="reference internal" href="email.policy.html#email.policy.Policy.mangle_from_" title="email.policy.Policy.mangle_from_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mangle_from_</span></code></a>343setting of the <em>policy</em> (which is <code class="docutils literal notranslate"><span class="pre">True</span></code> for the344<a class="reference internal" href="email.policy.html#email.policy.compat32" title="email.policy.compat32"><code class="xref py py-data docutils literal notranslate"><span class="pre">compat32</span></code></a> policy and <code class="docutils literal notranslate"><span class="pre">False</span></code> for all others).345<em>mangle_from_</em> is intended for use when messages are stored in Unix mbox346format (see <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> and <a class="reference external" href="https://www.jwz.org/doc/content-length.html">WHY THE CONTENT-LENGTH FORMAT IS BAD</a>).</p>347<p>If <em>maxheaderlen</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, refold any header lines that are longer348than <em>maxheaderlen</em>, or if <code class="docutils literal notranslate"><span class="pre">0</span></code>, do not rewrap any headers. If349<em>manheaderlen</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), wrap headers and other message350lines according to the <em>policy</em> settings.</p>351<p>If <em>policy</em> is specified, use that policy to control message generation. If352<em>policy</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), use the policy associated with the353<a class="reference internal" href="email.compat32-message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> or <a class="reference internal" href="email.message.html#email.message.EmailMessage" title="email.message.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a>354object passed to <code class="docutils literal notranslate"><span class="pre">flatten</span></code> to control the message generation. See355<a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.policy</span></code></a> for details on what <em>policy</em> controls.</p>356<div class="versionchanged">357<p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>policy</em> keyword.</p>358</div>359<div class="versionchanged">360<p><span class="versionmodified changed">Changed in version 3.6: </span>The default behavior of the <em>mangle_from_</em>361and <em>maxheaderlen</em> parameters is to follow the policy.</p>362</div>363<dl class="py method">364<dt class="sig sig-object py" id="email.generator.Generator.flatten">365<span class="sig-name descname"><span class="pre">flatten</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">msg</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">unixfrom</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">linesep</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.flatten" title="Link to this definition">¶</a></dt>366<dd><p>Print the textual representation of the message object structure rooted367at <em>msg</em> to the output file specified when the <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code>368instance was created.</p>369<p>If the <a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">policy</span></code></a> option <a class="reference internal" href="email.policy.html#email.policy.Policy.cte_type" title="email.policy.Policy.cte_type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">cte_type</span></code></a>370is <code class="docutils literal notranslate"><span class="pre">8bit</span></code>, generate the message as if the option were set to <code class="docutils literal notranslate"><span class="pre">7bit</span></code>.371(This is required because strings cannot represent non-ASCII bytes.)372Convert any bytes with the high bit set as needed using an373ASCII-compatible <em class="mailheader">Content-Transfer-Encoding</em>. That is,374transform parts with non-ASCII <em class="mailheader">Content-Transfer-Encoding</em>375(<em class="mailheader">Content-Transfer-Encoding: 8bit</em>) to an ASCII compatible376<em class="mailheader">Content-Transfer-Encoding</em>, and encode RFC-invalid non-ASCII377bytes in headers using the MIME <code class="docutils literal notranslate"><span class="pre">unknown-8bit</span></code> character set, thus378rendering them RFC-compliant.</p>379<p>If <em>unixfrom</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, print the envelope header delimiter used by380the Unix mailbox format (see <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a>) before the first of the381<span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5322.html"><strong>RFC 5322</strong></a> headers of the root message object. If the root object has382no envelope header, craft a standard one. The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>.383Note that for subparts, no envelope header is ever printed.</p>384<p>If <em>linesep</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, use it as the separator character between385all the lines of the flattened message. If <em>linesep</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the386default), use the value specified in the <em>policy</em>.</p>387<div class="versionchanged">388<p><span class="versionmodified changed">Changed in version 3.2: </span>Added support for re-encoding <code class="docutils literal notranslate"><span class="pre">8bit</span></code> message bodies, and the389<em>linesep</em> argument.</p>390</div>391</dd></dl>392 393<dl class="py method">394<dt class="sig sig-object py" id="email.generator.Generator.clone">395<span class="sig-name descname"><span class="pre">clone</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fp</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.clone" title="Link to this definition">¶</a></dt>396<dd><p>Return an independent clone of this <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code> instance with the397exact same options, and <em>fp</em> as the new <em>outfp</em>.</p>398</dd></dl>399 400<dl class="py method">401<dt class="sig sig-object py" id="email.generator.Generator.write">402<span class="sig-name descname"><span class="pre">write</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">s</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.write" title="Link to this definition">¶</a></dt>403<dd><p>Write <em>s</em> to the <em>write</em> method of the <em>outfp</em> passed to the404<code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code>’s constructor. This provides just enough file-like405API for <code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code> instances to be used in the <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a>406function.</p>407</dd></dl>408 409</dd></dl>410 411<p>As a convenience, <a class="reference internal" href="email.message.html#email.message.EmailMessage" title="email.message.EmailMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailMessage</span></code></a> provides the methods412<a class="reference internal" href="email.message.html#email.message.EmailMessage.as_string" title="email.message.EmailMessage.as_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_string()</span></code></a> and <code class="docutils literal notranslate"><span class="pre">str(aMessage)</span></code> (a.k.a.413<a class="reference internal" href="email.message.html#email.message.EmailMessage.__str__" title="email.message.EmailMessage.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>), which simplify the generation of414a formatted string representation of a message object. For more detail, see415<a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a>.</p>416<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code> module also provides a derived class,417<a class="reference internal" href="#email.generator.DecodedGenerator" title="email.generator.DecodedGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecodedGenerator</span></code></a>, which is like the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> base class,418except that non-<em class="mimetype">text</em> parts are not serialized, but are instead419represented in the output stream by a string derived from a template filled420in with information about the part.</p>421<dl class="py class">422<dt class="sig sig-object py" id="email.generator.DecodedGenerator">423<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">email.generator.</span></span><span class="sig-name descname"><span class="pre">DecodedGenerator</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">outfp</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">mangle_from_</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">maxheaderlen</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fmt</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">policy</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.DecodedGenerator" title="Link to this definition">¶</a></dt>424<dd><p>Act like <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a>, except that for any subpart of the message425passed to <a class="reference internal" href="#email.generator.Generator.flatten" title="email.generator.Generator.flatten"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Generator.flatten()</span></code></a>, if the subpart is of main type426<em class="mimetype">text</em>, print the decoded payload of the subpart, and if the main427type is not <em class="mimetype">text</em>, instead of printing it fill in the string428<em>fmt</em> using information from the part and print the resulting429filled-in string.</p>430<p>To fill in <em>fmt</em>, execute <code class="docutils literal notranslate"><span class="pre">fmt</span> <span class="pre">%</span> <span class="pre">part_info</span></code>, where <code class="docutils literal notranslate"><span class="pre">part_info</span></code>431is a dictionary composed of the following keys and values:</p>432<ul class="simple">433<li><p><code class="docutils literal notranslate"><span class="pre">type</span></code> – Full MIME type of the non-<em class="mimetype">text</em> part</p></li>434<li><p><code class="docutils literal notranslate"><span class="pre">maintype</span></code> – Main MIME type of the non-<em class="mimetype">text</em> part</p></li>435<li><p><code class="docutils literal notranslate"><span class="pre">subtype</span></code> – Sub-MIME type of the non-<em class="mimetype">text</em> part</p></li>436<li><p><code class="docutils literal notranslate"><span class="pre">filename</span></code> – Filename of the non-<em class="mimetype">text</em> part</p></li>437<li><p><code class="docutils literal notranslate"><span class="pre">description</span></code> – Description associated with the non-<em class="mimetype">text</em> part</p></li>438<li><p><code class="docutils literal notranslate"><span class="pre">encoding</span></code> – Content transfer encoding of the non-<em class="mimetype">text</em> part</p></li>439</ul>440<p>If <em>fmt</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, use the following default <em>fmt</em>:</p>441<blockquote>442<div><p>“[Non-text (%(type)s) part of message omitted, filename %(filename)s]”</p>443</div></blockquote>444<p>Optional <em>_mangle_from_</em> and <em>maxheaderlen</em> are as with the445<a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> base class.</p>446</dd></dl>447 448<p class="rubric">Footnotes</p>449<aside class="footnote-list brackets">450<aside class="footnote brackets" id="id3" role="doc-footnote">451<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>452<p>This statement assumes that you use the appropriate setting for453<code class="docutils literal notranslate"><span class="pre">unixfrom</span></code>, and that there are no <a class="reference internal" href="email.policy.html#module-email.policy" title="email.policy: Controlling the parsing and generating of messages"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.policy</span></code></a> settings calling for454automatic adjustments (for example,455<a class="reference internal" href="email.policy.html#email.policy.EmailPolicy.refold_source" title="email.policy.EmailPolicy.refold_source"><code class="xref py py-attr docutils literal notranslate"><span class="pre">refold_source</span></code></a> must be <code class="docutils literal notranslate"><span class="pre">none</span></code>, which is456<em>not</em> the default). It is also not 100% true, since if the message457does not conform to the RFC standards occasionally information about the458exact original text is lost during parsing error recovery. It is a goal459to fix these latter edge cases when possible.</p>460</aside>461</aside>462</section>463 464 465 <div class="clearer"></div>466 </div>467 </div>468 </div>469 <div class="sphinxsidebar" role="navigation" aria-label="Main">470 <div class="sphinxsidebarwrapper">471 <div>472 <h4>Previous topic</h4>473 <p class="topless"><a href="email.parser.html"474 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a></p>475 </div>476 <div>477 <h4>Next topic</h4>478 <p class="topless"><a href="email.policy.html"479 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.policy</span></code>: Policy Objects</a></p>480 </div>481 <script>482 document.addEventListener('DOMContentLoaded', () => {483 const title = document.querySelector('meta[property="og:title"]').content;484 const elements = document.querySelectorAll('.improvepage');485 const pageurl = window.location.href.split('?')[0];486 elements.forEach(element => {487 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));488 url.searchParams.set('pagetitle', title);489 url.searchParams.set('pageurl', pageurl);490 url.searchParams.set('pagesource', "library/email.generator.rst");491 element.href = url.toString();492 });493 });494 </script>495 <div role="note" aria-label="source link">496 <h3>This page</h3>497 <ul class="this-page-menu">498 <li><a href="../bugs.html">Report a bug</a></li>499 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>500 <li>501 <a href="https://github.com/python/cpython/blob/main/Doc/library/email.generator.rst?plain=1"502 rel="nofollow">Show source503 </a>504 </li>505 506 </ul>507 </div>508 </div>509<div id="sidebarbutton" title="Collapse sidebar">510<span>«</span>511</div>512 513 </div>514 <div class="clearer"></div>515 </div> 516 <div class="related" role="navigation" aria-label="Related">517 <h3>Navigation</h3>518 <ul>519 <li class="right" style="margin-right: 10px">520 <a href="../genindex.html" title="General Index"521 >index</a></li>522 <li class="right" >523 <a href="../py-modindex.html" title="Python Module Index"524 >modules</a> |</li>525 <li class="right" >526 <a href="email.policy.html" title="email.policy: Policy Objects"527 >next</a> |</li>528 <li class="right" >529 <a href="email.parser.html" title="email.parser: Parsing email messages"530 >previous</a> |</li>531 532 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>533 <li><a href="https://www.python.org/">Python</a> »</li>534 <li class="switchers">535 <div class="language_switcher_placeholder"></div>536 <div class="version_switcher_placeholder"></div>537 </li>538 <li>539 540 </li>541 <li id="cpython-language-and-version">542 <a href="../index.html">3.15.0a6 Documentation</a> »543 </li>544 545 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>546 <li class="nav-item nav-item-2"><a href="netdata.html" >Internet Data Handling</a> »</li>547 <li class="nav-item nav-item-3"><a href="email.html" ><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> »</li>548 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></li>549 <li class="right">550 551 552 <div class="inline-search" role="search">553 <form class="inline-search" action="../search.html" method="get">554 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">555 <input type="submit" value="Go">556 </form>557 </div>558 |559 </li>560 <li class="right">561<label class="theme-selector-label">562 Theme563 <select class="theme-selector" oninput="activateTheme(this.value)">564 <option value="auto" selected>Auto</option>565 <option value="light">Light</option>566 <option value="dark">Dark</option>567 </select>568</label> |</li>569 570 </ul>571 </div> 572 <div class="footer">573 © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.574 <br>575 This page is licensed under the Python Software Foundation License Version 2.576 <br>577 Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.578 <br>579 580 See <a href="/license.html">History and License</a> for more information.<br>581 582 583 <br>584 585 The Python Software Foundation is a non-profit corporation.586<a href="https://www.python.org/psf/donations/">Please donate.</a>587<br>588 <br>589 Last updated on Mar 10, 2026 (08:58 UTC).590 591 <a href="/bugs.html">Found a bug</a>?592 593 <br>594 595 Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.596 </div>597 598 </body>599</html>