"""Send the contents of a directory as a MIME message.
Usage: dirmail [options] from to [to ...]*
Print this message and exit.
Mail the contents of the specified directory, otherwise use the
current directory. Only the regular files in the directory are sent,
and we don't recurse to subdirectories.
`from' is the email address of the sender of the message.
`to' is the email address of the recipient of the message, and multiple
The email is sent by forwarding to your local SMTP server, which then does the
normal delivery process. Your local machine must be running an SMTP server.
# For guessing MIME type based on file name extension
from email
import Encoders
from email
.Message
import Message
from email
.MIMEAudio
import MIMEAudio
from email
.MIMEBase
import MIMEBase
from email
.MIMEMultipart
import MIMEMultipart
from email
.MIMEImage
import MIMEImage
from email
.MIMEText
import MIMEText
print >> sys
.stderr
, __doc__
opts
, args
= getopt
.getopt(sys
.argv
[1:], 'hd:', ['help', 'directory='])
except getopt
.error
, msg
:
if opt
in ('-h', '--help'):
elif opt
in ('-d', '--directory'):
# Create the enclosing (outer) message
outer
['Subject'] = 'Contents of directory %s' % os
.path
.abspath(dir)
outer
['To'] = COMMASPACE
.join(recips
)
outer
.preamble
= 'You will not see this in a MIME-aware mail reader.\n'
# To guarantee the message ends with a newline
for filename
in os
.listdir(dir):
path
= os
.path
.join(dir, filename
)
if not os
.path
.isfile(path
):
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype
, encoding
= mimetypes
.guess_type(path
)
if ctype
is None or encoding
is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype
= 'application/octet-stream'
maintype
, subtype
= ctype
.split('/', 1)
# Note: we should handle calculating the charset
msg
= MIMEText(fp
.read(), _subtype
=subtype
)
elif maintype
== 'image':
msg
= MIMEImage(fp
.read(), _subtype
=subtype
)
elif maintype
== 'audio':
msg
= MIMEAudio(fp
.read(), _subtype
=subtype
)
msg
= MIMEBase(maintype
, subtype
)
msg
.set_payload(fp
.read())
# Encode the payload using Base64
Encoders
.encode_base64(msg
)
# Set the filename parameter
msg
.add_header('Content-Disposition', 'attachment', filename
=filename
)
s
.sendmail(sender
, recips
, outer
.as_string())
if __name__
== '__main__':