test_whitespace_eater_unicode(): Make this test Python 2.1 compatible.
[python/dscho.git] / Doc / lib / email-dir.py
blobaa3b5e519196324aaf05b408391b79848b7eff67
1 #!/usr/bin/env python
3 """Send the contents of a directory as a MIME message.
5 Usage: dirmail [options] from to [to ...]*
7 Options:
8 -h / --help
9 Print this message and exit.
11 -d directory
12 --directory=directory
13 Mail the contents of the specified directory, otherwise use the
14 current directory. Only the regular files in the directory are sent,
15 and we don't recurse to subdirectories.
17 `from' is the email address of the sender of the message.
19 `to' is the email address of the recipient of the message, and multiple
20 recipients may be given.
22 The email is sent by forwarding to your local SMTP server, which then does the
23 normal delivery process. Your local machine must be running an SMTP server.
24 """
26 import sys
27 import os
28 import getopt
29 import smtplib
30 # For guessing MIME type based on file name extension
31 import mimetypes
33 from email import Encoders
34 from email.Message import Message
35 from email.MIMEAudio import MIMEAudio
36 from email.MIMEMultipart import MIMEMultipart
37 from email.MIMEImage import MIMEImage
38 from email.MIMEText import MIMEText
40 COMMASPACE = ', '
43 def usage(code, msg=''):
44 print >> sys.stderr, __doc__
45 if msg:
46 print >> sys.stderr, msg
47 sys.exit(code)
50 def main():
51 try:
52 opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory='])
53 except getopt.error, msg:
54 usage(1, msg)
56 dir = os.curdir
57 for opt, arg in opts:
58 if opt in ('-h', '--help'):
59 usage(0)
60 elif opt in ('-d', '--directory'):
61 dir = arg
63 if len(args) < 2:
64 usage(1)
66 sender = args[0]
67 recips = args[1:]
69 # Create the enclosing (outer) message
70 outer = MIMEMultipart()
71 outer['Subject'] = 'Contents of directory %s' % os.path.abspath(dir)
72 outer['To'] = COMMASPACE.join(recips)
73 outer['From'] = sender
74 outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
75 # To guarantee the message ends with a newline
76 outer.epilogue = ''
78 for filename in os.listdir(dir):
79 path = os.path.join(dir, filename)
80 if not os.path.isfile(path):
81 continue
82 # Guess the content type based on the file's extension. Encoding
83 # will be ignored, although we should check for simple things like
84 # gzip'd or compressed files.
85 ctype, encoding = mimetypes.guess_type(path)
86 if ctype is None or encoding is not None:
87 # No guess could be made, or the file is encoded (compressed), so
88 # use a generic bag-of-bits type.
89 ctype = 'application/octet-stream'
90 maintype, subtype = ctype.split('/', 1)
91 if maintype == 'text':
92 fp = open(path)
93 # Note: we should handle calculating the charset
94 msg = MIMEText(fp.read(), _subtype=subtype)
95 fp.close()
96 elif maintype == 'image':
97 fp = open(path, 'rb')
98 msg = MIMEImage(fp.read(), _subtype=subtype)
99 fp.close()
100 elif maintype == 'audio':
101 fp = open(path, 'rb')
102 msg = MIMEAudio(fp.read(), _subtype=subtype)
103 fp.close()
104 else:
105 fp = open(path, 'rb')
106 msg = MIMEBase(maintype, subtype)
107 msg.set_payload(fp.read())
108 fp.close()
109 # Encode the payload using Base64
110 Encoders.encode_base64(msg)
111 # Set the filename parameter
112 msg.add_header('Content-Disposition', 'attachment', filename=filename)
113 outer.attach(msg)
115 # Now send the message
116 s = smtplib.SMTP()
117 s.connect()
118 s.sendmail(sender, recips, outer.as_string())
119 s.close()
122 if __name__ == '__main__':
123 main()