Commit f9e3cf1f authored by Berker Peksag's avatar Berker Peksag

Issue #23511: Port email-simple.py to Python 3.

Also, update email examples to use the context manager version of open().

Patch by Baptiste Mispelon.
parent b808d590
# Import the email modules we'll need # Import the email modules we'll need
from email.parser import Parser from email.parser import Parser
# If the e-mail headers are in a file, uncomment this line: # If the e-mail headers are in a file, uncomment these two lines:
#headers = Parser().parse(open(messagefile, 'r')) # with open(messagefile) as fp:
# headers = Parser().parse(fp)
# Or for parsing headers in a string, use: # Or for parsing headers in a string, use:
headers = Parser().parsestr('From: <user@example.com>\n' headers = Parser().parsestr('From: <user@example.com>\n'
......
...@@ -20,9 +20,8 @@ msg.preamble = 'Our family reunion' ...@@ -20,9 +20,8 @@ msg.preamble = 'Our family reunion'
for file in pngfiles: for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically # Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type. # guess the specific image type.
fp = open(file, 'rb') with open(file, 'rb') as fp:
img = MIMEImage(fp.read()) img = MIMEImage(fp.read())
fp.close()
msg.attach(img) msg.attach(img)
# Send the email via our own SMTP server. # Send the email via our own SMTP server.
......
...@@ -12,7 +12,8 @@ from email.parser import BytesParser ...@@ -12,7 +12,8 @@ from email.parser import BytesParser
from imaginary import magic_html_parser from imaginary import magic_html_parser
# In a real program you'd get the filename from the arguments. # 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 # Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode: # be converted to unicode:
......
...@@ -6,10 +6,9 @@ from email.mime.text import MIMEText ...@@ -6,10 +6,9 @@ from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that # Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters. # the text file contains only ASCII characters.
fp = open(textfile, 'rb') with open(textfile) as fp:
# Create a text/plain message # Create a text/plain message
msg = MIMEText(fp.read()) msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address # me == the sender's email address
# you == the recipient's email address # you == the recipient's email address
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment