(root)/
Python-3.11.7/
Doc/
includes/
email-alternative.py
       1  #!/usr/bin/env python3
       2  
       3  import smtplib
       4  
       5  from email.message import EmailMessage
       6  from email.headerregistry import Address
       7  from email.utils import make_msgid
       8  
       9  # Create the base text message.
      10  msg = EmailMessage()
      11  msg['Subject'] = "Ayons asperges pour le déjeuner"
      12  msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
      13  msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
      14               Address("Fabrette Pussycat", "fabrette", "example.com"))
      15  msg.set_content("""\
      16  Salut!
      17  
      18  Cela ressemble à un excellent recipie[1] déjeuner.
      19  
      20  [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
      21  
      22  --Pepé
      23  """)
      24  
      25  # Add the html version.  This converts the message into a multipart/alternative
      26  # container, with the original text message as the first part and the new html
      27  # message as the second part.
      28  asparagus_cid = make_msgid()
      29  msg.add_alternative("""\
      30  <html>
      31    <head></head>
      32    <body>
      33      <p>Salut!</p>
      34      <p>Cela ressemble à un excellent
      35          <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
      36              recipie
      37          </a> déjeuner.
      38      </p>
      39      <img src="cid:{asparagus_cid}" />
      40    </body>
      41  </html>
      42  """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
      43  # note that we needed to peel the <> off the msgid for use in the html.
      44  
      45  # Now add the related image to the html part.
      46  with open("roasted-asparagus.jpg", 'rb') as img:
      47      msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
      48                                       cid=asparagus_cid)
      49  
      50  # Make a local copy of what we are going to send.
      51  with open('outgoing.msg', 'wb') as f:
      52      f.write(bytes(msg))
      53  
      54  # Send the message via local SMTP server.
      55  with smtplib.SMTP('localhost') as s:
      56      s.send_message(msg)