Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f9e3cf1

Browse files
committed
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.
1 parent b808d59 commit f9e3cf1

4 files changed

Lines changed: 10 additions & 10 deletions

File tree

Doc/includes/email-headers.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Import the email modules we'll need
22
from email.parser import Parser
33

4-
# If the e-mail headers are in a file, uncomment this line:
5-
#headers = Parser().parse(open(messagefile, 'r'))
4+
# If the e-mail headers are in a file, uncomment these two lines:
5+
# with open(messagefile) as fp:
6+
# headers = Parser().parse(fp)
67

78
# Or for parsing headers in a string, use:
89
headers = Parser().parsestr('From: <[email protected]>\n'

Doc/includes/email-mime.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,8 @@
2020
for file in pngfiles:
2121
# Open the files in binary mode. Let the MIMEImage class automatically
2222
# guess the specific image type.
23-
fp = open(file, 'rb')
24-
img = MIMEImage(fp.read())
25-
fp.close()
23+
with open(file, 'rb') as fp:
24+
img = MIMEImage(fp.read())
2625
msg.attach(img)
2726

2827
# Send the email via our own SMTP server.

Doc/includes/email-read-alternative-new-api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
from imaginary import magic_html_parser
1313

1414
# In a real program you'd get the filename from the arguments.
15-
msg = BytesParser(policy=policy.default).parse(open('outgoing.msg', 'rb'))
15+
with open('outgoing.msg', 'rb') as fp:
16+
msg = BytesParser(policy=policy.default).parse(fp)
1617

1718
# Now the header items can be accessed as a dictionary, and any non-ASCII will
1819
# be converted to unicode:

Doc/includes/email-simple.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@
66

77
# Open a plain text file for reading. For this example, assume that
88
# the text file contains only ASCII characters.
9-
fp = open(textfile, 'rb')
10-
# Create a text/plain message
11-
msg = MIMEText(fp.read())
12-
fp.close()
9+
with open(textfile) as fp:
10+
# Create a text/plain message
11+
msg = MIMEText(fp.read())
1312

1413
# me == the sender's email address
1514
# you == the recipient's email address

0 commit comments

Comments
 (0)