(root)/
Python-3.11.7/
Doc/
includes/
email-dir.py
       1  #!/usr/bin/env python3
       2  
       3  """Send the contents of a directory as a MIME message."""
       4  
       5  import os
       6  import smtplib
       7  # For guessing MIME type based on file name extension
       8  import mimetypes
       9  
      10  from argparse import ArgumentParser
      11  
      12  from email.message import EmailMessage
      13  from email.policy import SMTP
      14  
      15  
      16  def main():
      17      parser = ArgumentParser(description="""\
      18  Send the contents of a directory as a MIME message.
      19  Unless the -o option is given, the email is sent by forwarding to your local
      20  SMTP server, which then does the normal delivery process.  Your local machine
      21  must 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_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)
      74  
      75  
      76  if __name__ == '__main__':
      77      main()