MCPcopy Index your code
hub / github.com/python/cpython / main

Function main

Doc/includes/email-dir.py:16–73  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

14
15
16def main():
17 parser = ArgumentParser(description="""\
18Send the contents of a directory as a MIME message.
19Unless the -o option is given, the email is sent by forwarding to your local
20SMTP server, which then does the normal delivery process. Your local machine
21must be running an SMTP server.
22""")
23 parser.add_argument('-d', '--directory',
24 help="""Mail the contents of the specified directory,
25 otherwise use the current directory. Only the regular
26 files in the directory are sent, and we don't recurse to
27 subdirectories.""")
28 parser.add_argument('-o', '--output',
29 metavar='FILE',
30 help="""Print the composed message to FILE instead of
31 sending the message to the SMTP server.""")
32 parser.add_argument('-s', '--sender', required=True,
33 help='The value of the From: header (required)')
34 parser.add_argument('-r', '--recipient', required=True,
35 action='append', metavar='RECIPIENT',
36 default=[], dest='recipients',
37 help='A To: header value (at least one required)')
38 args = parser.parse_args()
39 directory = args.directory
40 if not directory:
41 directory = '.'
42 # Create the message
43 msg = EmailMessage()
44 msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'
45 msg['To'] = ', '.join(args.recipients)
46 msg['From'] = args.sender
47 msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
48
49 for filename in os.listdir(directory):
50 path = os.path.join(directory, filename)
51 if not os.path.isfile(path):
52 continue
53 # Guess the content type based on the file's extension. Encoding
54 # will be ignored, although we should check for simple things like
55 # gzip'd or compressed files.
56 ctype, encoding = mimetypes.guess_file_type(path)
57 if ctype is None or encoding is not None:
58 # No guess could be made, or the file is encoded (compressed), so
59 # use a generic bag-of-bits type.
60 ctype = 'application/octet-stream'
61 maintype, subtype = ctype.split('/', 1)
62 with open(path, 'rb') as fp:
63 msg.add_attachment(fp.read(),
64 maintype=maintype,
65 subtype=subtype,
66 filename=filename)
67 # Now send or store the message
68 if args.output:
69 with open(args.output, 'wb') as fp:
70 fp.write(msg.as_bytes(policy=SMTP))
71 else:
72 with smtplib.SMTP('localhost') as s:
73 s.send_message(msg)

Callers 1

email-dir.pyFile · 0.70

Calls 15

parse_argsMethod · 0.95
ArgumentParserClass · 0.90
EmailMessageClass · 0.90
listdirMethod · 0.80
guess_file_typeMethod · 0.80
add_attachmentMethod · 0.80
as_bytesMethod · 0.80
send_messageMethod · 0.80
openFunction · 0.50
add_argumentMethod · 0.45
abspathMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…