Issue #18972: Modernize email examples and use the argparse module in them.
This commit is contained in:
parent
ce28e2c24b
commit
992cf1dd59
@ -8,7 +8,7 @@ import smtplib
|
|||||||
# For guessing MIME type based on file name extension
|
# For guessing MIME type based on file name extension
|
||||||
import mimetypes
|
import mimetypes
|
||||||
|
|
||||||
from optparse import OptionParser
|
from argparse import ArgumentParser
|
||||||
|
|
||||||
from email import encoders
|
from email import encoders
|
||||||
from email.message import Message
|
from email.message import Message
|
||||||
@ -22,44 +22,36 @@ COMMASPACE = ', '
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = OptionParser(usage="""\
|
parser = ArgumentParser(description="""\
|
||||||
Send the contents of a directory as a MIME message.
|
Send the contents of a directory as a MIME message.
|
||||||
|
|
||||||
Usage: %prog [options]
|
|
||||||
|
|
||||||
Unless the -o option is given, the email is sent by forwarding to your local
|
Unless the -o option is given, the email is sent by forwarding to your local
|
||||||
SMTP server, which then does the normal delivery process. Your local machine
|
SMTP server, which then does the normal delivery process. Your local machine
|
||||||
must be running an SMTP server.
|
must be running an SMTP server.
|
||||||
""")
|
""")
|
||||||
parser.add_option('-d', '--directory',
|
parser.add_argument('-d', '--directory',
|
||||||
type='string', action='store',
|
help="""Mail the contents of the specified directory,
|
||||||
help="""Mail the contents of the specified directory,
|
otherwise use the current directory. Only the regular
|
||||||
otherwise use the current directory. Only the regular
|
files in the directory are sent, and we don't recurse to
|
||||||
files in the directory are sent, and we don't recurse to
|
subdirectories.""")
|
||||||
subdirectories.""")
|
parser.add_argument('-o', '--output',
|
||||||
parser.add_option('-o', '--output',
|
metavar='FILE',
|
||||||
type='string', action='store', metavar='FILE',
|
help="""Print the composed message to FILE instead of
|
||||||
help="""Print the composed message to FILE instead of
|
sending the message to the SMTP server.""")
|
||||||
sending the message to the SMTP server.""")
|
parser.add_argument('-s', '--sender', required=True,
|
||||||
parser.add_option('-s', '--sender',
|
help='The value of the From: header (required)')
|
||||||
type='string', action='store', metavar='SENDER',
|
parser.add_argument('-r', '--recipient', required=True,
|
||||||
help='The value of the From: header (required)')
|
action='append', metavar='RECIPIENT',
|
||||||
parser.add_option('-r', '--recipient',
|
default=[], dest='recipients',
|
||||||
type='string', action='append', metavar='RECIPIENT',
|
help='A To: header value (at least one required)')
|
||||||
default=[], dest='recipients',
|
args = parser.parse_args()
|
||||||
help='A To: header value (at least one required)')
|
directory = args.directory
|
||||||
opts, args = parser.parse_args()
|
|
||||||
if not opts.sender or not opts.recipients:
|
|
||||||
parser.print_help()
|
|
||||||
sys.exit(1)
|
|
||||||
directory = opts.directory
|
|
||||||
if not directory:
|
if not directory:
|
||||||
directory = '.'
|
directory = '.'
|
||||||
# Create the enclosing (outer) message
|
# Create the enclosing (outer) message
|
||||||
outer = MIMEMultipart()
|
outer = MIMEMultipart()
|
||||||
outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
|
outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
|
||||||
outer['To'] = COMMASPACE.join(opts.recipients)
|
outer['To'] = COMMASPACE.join(args.recipients)
|
||||||
outer['From'] = opts.sender
|
outer['From'] = args.sender
|
||||||
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
|
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
|
||||||
|
|
||||||
for filename in os.listdir(directory):
|
for filename in os.listdir(directory):
|
||||||
@ -76,23 +68,19 @@ must be running an SMTP server.
|
|||||||
ctype = 'application/octet-stream'
|
ctype = 'application/octet-stream'
|
||||||
maintype, subtype = ctype.split('/', 1)
|
maintype, subtype = ctype.split('/', 1)
|
||||||
if maintype == 'text':
|
if maintype == 'text':
|
||||||
fp = open(path)
|
with open(path) as fp:
|
||||||
# Note: we should handle calculating the charset
|
# Note: we should handle calculating the charset
|
||||||
msg = MIMEText(fp.read(), _subtype=subtype)
|
msg = MIMEText(fp.read(), _subtype=subtype)
|
||||||
fp.close()
|
|
||||||
elif maintype == 'image':
|
elif maintype == 'image':
|
||||||
fp = open(path, 'rb')
|
with open(path, 'rb') as fp:
|
||||||
msg = MIMEImage(fp.read(), _subtype=subtype)
|
msg = MIMEImage(fp.read(), _subtype=subtype)
|
||||||
fp.close()
|
|
||||||
elif maintype == 'audio':
|
elif maintype == 'audio':
|
||||||
fp = open(path, 'rb')
|
with open(path, 'rb') as fp:
|
||||||
msg = MIMEAudio(fp.read(), _subtype=subtype)
|
msg = MIMEAudio(fp.read(), _subtype=subtype)
|
||||||
fp.close()
|
|
||||||
else:
|
else:
|
||||||
fp = open(path, 'rb')
|
with open(path, 'rb') as fp:
|
||||||
msg = MIMEBase(maintype, subtype)
|
msg = MIMEBase(maintype, subtype)
|
||||||
msg.set_payload(fp.read())
|
msg.set_payload(fp.read())
|
||||||
fp.close()
|
|
||||||
# Encode the payload using Base64
|
# Encode the payload using Base64
|
||||||
encoders.encode_base64(msg)
|
encoders.encode_base64(msg)
|
||||||
# Set the filename parameter
|
# Set the filename parameter
|
||||||
@ -100,14 +88,12 @@ must be running an SMTP server.
|
|||||||
outer.attach(msg)
|
outer.attach(msg)
|
||||||
# Now send or store the message
|
# Now send or store the message
|
||||||
composed = outer.as_string()
|
composed = outer.as_string()
|
||||||
if opts.output:
|
if args.output:
|
||||||
fp = open(opts.output, 'w')
|
with open(args.output, 'w') as fp:
|
||||||
fp.write(composed)
|
fp.write(composed)
|
||||||
fp.close()
|
|
||||||
else:
|
else:
|
||||||
s = smtplib.SMTP('localhost')
|
with smtplib.SMTP('localhost') as s:
|
||||||
s.sendmail(opts.sender, opts.recipients, composed)
|
s.sendmail(args.sender, args.recipients, composed)
|
||||||
s.quit()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -8,41 +8,27 @@ import email
|
|||||||
import errno
|
import errno
|
||||||
import mimetypes
|
import mimetypes
|
||||||
|
|
||||||
from optparse import OptionParser
|
from argparse import ArgumentParser
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = OptionParser(usage="""\
|
parser = ArgumentParser(description="""\
|
||||||
Unpack a MIME message into a directory of files.
|
Unpack a MIME message into a directory of files.
|
||||||
|
|
||||||
Usage: %prog [options] msgfile
|
|
||||||
""")
|
""")
|
||||||
parser.add_option('-d', '--directory',
|
parser.add_argument('-d', '--directory', required=True,
|
||||||
type='string', action='store',
|
help="""Unpack the MIME message into the named
|
||||||
help="""Unpack the MIME message into the named
|
directory, which will be created if it doesn't already
|
||||||
directory, which will be created if it doesn't already
|
exist.""")
|
||||||
exist.""")
|
parser.add_argument('msgfile')
|
||||||
opts, args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if not opts.directory:
|
|
||||||
parser.print_help()
|
with open(args.msgfile) as fp:
|
||||||
sys.exit(1)
|
msg = email.message_from_file(fp)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
msgfile = args[0]
|
os.mkdir(args.directory)
|
||||||
except IndexError:
|
except FileExistsError:
|
||||||
parser.print_help()
|
pass
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
try:
|
|
||||||
os.mkdir(opts.directory)
|
|
||||||
except OSError as e:
|
|
||||||
# Ignore directory exists error
|
|
||||||
if e.errno != errno.EEXIST:
|
|
||||||
raise
|
|
||||||
|
|
||||||
fp = open(msgfile)
|
|
||||||
msg = email.message_from_file(fp)
|
|
||||||
fp.close()
|
|
||||||
|
|
||||||
counter = 1
|
counter = 1
|
||||||
for part in msg.walk():
|
for part in msg.walk():
|
||||||
@ -59,9 +45,8 @@ Usage: %prog [options] msgfile
|
|||||||
ext = '.bin'
|
ext = '.bin'
|
||||||
filename = 'part-%03d%s' % (counter, ext)
|
filename = 'part-%03d%s' % (counter, ext)
|
||||||
counter += 1
|
counter += 1
|
||||||
fp = open(os.path.join(opts.directory, filename), 'wb')
|
with open(os.path.join(args.directory, filename), 'wb') as fp:
|
||||||
fp.write(part.get_payload(decode=True))
|
fp.write(part.get_payload(decode=True))
|
||||||
fp.close()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -60,6 +60,11 @@ Library
|
|||||||
- Issue #4366: Fix building extensions on all platforms when --enable-shared
|
- Issue #4366: Fix building extensions on all platforms when --enable-shared
|
||||||
is used.
|
is used.
|
||||||
|
|
||||||
|
Documentation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
- Issue #18972: Modernize email examples and use the argparse module in them.
|
||||||
|
|
||||||
Build
|
Build
|
||||||
-----
|
-----
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user