Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fcc31b4

Browse files
committed
Split the long email package examples into separate files and use
\verbatiminput instead of the verbatim environment -- this does the "right thing" regarding page breaks in long examples for the typeset formats, and has nice benefits for the HTML version as well.
1 parent ea66abc commit fcc31b4

5 files changed

Lines changed: 269 additions & 273 deletions

File tree

Doc/lib/email-dir.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
#!/usr/bin/env python
2+
3+
"""Send the contents of a directory as a MIME message.
4+
5+
Usage: dirmail [options] from to [to ...]*
6+
7+
Options:
8+
-h / --help
9+
Print this message and exit.
10+
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.
16+
17+
`from' is the email address of the sender of the message.
18+
19+
`to' is the email address of the recipient of the message, and multiple
20+
recipients may be given.
21+
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+
"""
25+
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
32+
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
39+
40+
COMMASPACE = ', '
41+
42+
43+
def usage(code, msg=''):
44+
print >> sys.stderr, __doc__
45+
if msg:
46+
print >> sys.stderr, msg
47+
sys.exit(code)
48+
49+
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)
55+
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
62+
63+
if len(args) < 2:
64+
usage(1)
65+
66+
sender = args[0]
67+
recips = args[1:]
68+
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 = ''
77+
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)
114+
115+
# Now send the message
116+
s = smtplib.SMTP()
117+
s.connect()
118+
s.sendmail(sender, recips, outer.as_string())
119+
s.close()
120+
121+
122+
if __name__ == '__main__':
123+
main()

Doc/lib/email-mime.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Import smtplib for the actual sending function
2+
import smtplib
3+
4+
# Here are the email pacakge modules we'll need
5+
from email.MIMEImage import MIMEImage
6+
from email.MIMEMultipart import MIMEMultipart
7+
8+
COMMASPACE = ', '
9+
10+
# Create the container (outer) email message.
11+
msg = MIMEMultipart()
12+
msg['Subject'] = 'Our family reunion'
13+
# me == the sender's email address
14+
# family = the list of all recipients' email addresses
15+
msg['From'] = me
16+
msg['To'] = COMMASPACE.join(family)
17+
msg.preamble = 'Our family reunion'
18+
# Guarantees the message ends in a newline
19+
msg.epilogue = ''
20+
21+
# Assume we know that the image files are all in PNG format
22+
for file in pngfiles:
23+
# Open the files in binary mode. Let the MIMEImage class automatically
24+
# guess the specific image type.
25+
fp = open(file, 'rb')
26+
img = MIMEImage(fp.read())
27+
fp.close()
28+
msg.attach(img)
29+
30+
# Send the email via our own SMTP server.
31+
s = smtplib.SMTP()
32+
s.connect()
33+
s.sendmail(me, family, msg.as_string())
34+
s.close()

Doc/lib/email-simple.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Import smtplib for the actual sending function
2+
import smtplib
3+
4+
# Import the email modules we'll need
5+
from email.MIMEText import MIMEText
6+
7+
# Open a plain text file for reading. For this example, assume that
8+
# the text file contains only ASCII characters.
9+
fp = open(textfile, 'rb')
10+
# Create a text/plain message
11+
msg = MIMEText(fp.read())
12+
fp.close()
13+
14+
# me == the sender's email address
15+
# you == the recipient's email address
16+
msg['Subject'] = 'The contents of %s' % textfile
17+
msg['From'] = me
18+
msg['To'] = you
19+
20+
# Send the message via our own SMTP server, but don't include the
21+
# envelope header.
22+
s = smtplib.SMTP()
23+
s.connect()
24+
s.sendmail(me, [you], msg.as_string())
25+
s.close()

Doc/lib/email-unpack.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env python
2+
3+
"""Unpack a MIME message into a directory of files.
4+
5+
Usage: unpackmail [options] msgfile
6+
7+
Options:
8+
-h / --help
9+
Print this message and exit.
10+
11+
-d directory
12+
--directory=directory
13+
Unpack the MIME message into the named directory, which will be
14+
created if it doesn't already exist.
15+
16+
msgfile is the path to the file containing the MIME message.
17+
"""
18+
19+
import sys
20+
import os
21+
import getopt
22+
import errno
23+
import mimetypes
24+
import email
25+
26+
27+
def usage(code, msg=''):
28+
print >> sys.stderr, __doc__
29+
if msg:
30+
print >> sys.stderr, msg
31+
sys.exit(code)
32+
33+
34+
def main():
35+
try:
36+
opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory='])
37+
except getopt.error, msg:
38+
usage(1, msg)
39+
40+
dir = os.curdir
41+
for opt, arg in opts:
42+
if opt in ('-h', '--help'):
43+
usage(0)
44+
elif opt in ('-d', '--directory'):
45+
dir = arg
46+
47+
try:
48+
msgfile = args[0]
49+
except IndexError:
50+
usage(1)
51+
52+
try:
53+
os.mkdir(dir)
54+
except OSError, e:
55+
# Ignore directory exists error
56+
if e.errno <> errno.EEXIST: raise
57+
58+
fp = open(msgfile)
59+
msg = email.message_from_file(fp)
60+
fp.close()
61+
62+
counter = 1
63+
for part in msg.walk():
64+
# multipart/* are just containers
65+
if part.get_content_maintype() == 'multipart':
66+
continue
67+
# Applications should really sanitize the given filename so that an
68+
# email message can't be used to overwrite important files
69+
filename = part.get_filename()
70+
if not filename:
71+
ext = mimetypes.guess_extension(part.get_type())
72+
if not ext:
73+
# Use a generic bag-of-bits extension
74+
ext = '.bin'
75+
filename = 'part-%03d%s' % (counter, ext)
76+
counter += 1
77+
fp = open(os.path.join(dir, filename), 'wb')
78+
fp.write(part.get_payload(decode=1))
79+
fp.close()
80+
81+
82+
if __name__ == '__main__':
83+
main()

0 commit comments

Comments
 (0)