]> granicus.if.org Git - python/commitdiff
Issue #23511: Port email-simple.py to Python 3.
authorBerker Peksag <berker.peksag@gmail.com>
Wed, 25 Feb 2015 16:14:09 +0000 (18:14 +0200)
committerBerker Peksag <berker.peksag@gmail.com>
Wed, 25 Feb 2015 16:14:09 +0000 (18:14 +0200)
Also, update email examples to use the context manager version of open().

Patch by Baptiste Mispelon.

Doc/includes/email-headers.py
Doc/includes/email-mime.py
Doc/includes/email-read-alternative-new-api.py
Doc/includes/email-simple.py

index a53317dbd84375e279aee45062a0361f954c0502..89c8f3af32f3017f67af55e7bad8074918215f8e 100644 (file)
@@ -1,8 +1,9 @@
 # Import the email modules we'll need
 from email.parser import Parser
 
-#  If the e-mail headers are in a file, uncomment this line:
-#headers = Parser().parse(open(messagefile, 'r'))
+# If the e-mail headers are in a file, uncomment these two lines:
+# with open(messagefile) as fp:
+#     headers = Parser().parse(fp)
 
 #  Or for parsing headers in a string, use:
 headers = Parser().parsestr('From: <user@example.com>\n'
index a90edc1373726ad6faa2397c1a475aa145f2da2b..61d08302a2cb9f41f2046c9d2416223f4abf1f38 100644 (file)
@@ -20,9 +20,8 @@ msg.preamble = 'Our family reunion'
 for file in pngfiles:
     # Open the files in binary mode.  Let the MIMEImage class automatically
     # guess the specific image type.
-    fp = open(file, 'rb')
-    img = MIMEImage(fp.read())
-    fp.close()
+    with open(file, 'rb') as fp:
+        img = MIMEImage(fp.read())
     msg.attach(img)
 
 # Send the email via our own SMTP server.
index 8ab4e9fd164dddbcf37561816db4e3f1e1a500d5..3f5ab24c0fbdd25361ae0f9035030f711fa157d5 100644 (file)
@@ -12,7 +12,8 @@ from email.parser import BytesParser
 from imaginary import magic_html_parser
 
 # In a real program you'd get the filename from the arguments.
-msg = BytesParser(policy=policy.default).parse(open('outgoing.msg', 'rb'))
+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:
index 077568d563be89530ed1666cc40cda4929abd6fa..b9b8b410a64320509a6d6aec45ca69a9546a921b 100644 (file)
@@ -6,10 +6,9 @@ from email.mime.text import MIMEText
 
 # Open a plain text file for reading.  For this example, assume that
 # the text file contains only ASCII characters.
-fp = open(textfile, 'rb')
-# Create a text/plain message
-msg = MIMEText(fp.read())
-fp.close()
+with open(textfile) as fp:
+    # Create a text/plain message
+    msg = MIMEText(fp.read())
 
 # me == the sender's email address
 # you == the recipient's email address