Difference between revisions of "Python: email"

From OnnoWiki
Jump to navigation Jump to search
(New page: Sumber: https://docs.python.org/2/library/email-examples.html Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more comp...)
 
 
Line 53: Line 53:
 
Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:
 
Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:
  
# Import smtplib for the actual sending function
+
# Import smtplib for the actual sending function
import smtplib
+
import smtplib
 
+
# Here are the email package modules we'll need
+
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
+
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
+
from email.mime.multipart import MIMEMultipart
 
+
COMMASPACE = ', '
+
COMMASPACE = ', '
 
+
# Create the container (outer) email message.
+
# Create the container (outer) email message.
msg = MIMEMultipart()
+
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
+
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
+
# me == the sender's email address
# family = the list of all recipients' email addresses
+
# family = the list of all recipients' email addresses
msg['From'] = me
+
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
+
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'
+
msg.preamble = 'Our family reunion'
 
+
# Assume we know that the image files are all in PNG format
+
# Assume we know that the image files are all in PNG format
for file in pngfiles:
+
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
+
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
+
    # guess the specific image type.
    fp = open(file, 'rb')
+
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
+
    img = MIMEImage(fp.read())
    fp.close()
+
    fp.close()
    msg.attach(img)
+
    msg.attach(img)  
 
+
# Send the email via our own SMTP server.
+
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
+
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
+
s.sendmail(me, family, msg.as_string())
s.quit()
+
s.quit()
  
 
Here’s an example of how to send the entire contents of a directory as an email message: [1]
 
Here’s an example of how to send the entire contents of a directory as an email message: [1]
  
#!/usr/bin/env python
+
#!/usr/bin/env python
 
+
"""Send the contents of a directory as a MIME message."""
+
"""Send the contents of a directory as a MIME message."""  
 
+
import os
+
import os
import sys
+
import sys
import smtplib
+
import smtplib
# For guessing MIME type based on file name extension
+
# For guessing MIME type based on file name extension
import mimetypes
+
import mimetypes
 
+
from optparse import OptionParser
+
from optparse import OptionParser
 
+
from email import encoders
+
from email import encoders
from email.message import Message
+
from email.message import Message
from email.mime.audio import MIMEAudio
+
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
+
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
+
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
+
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
+
from email.mime.text import MIMEText
 
+
COMMASPACE = ', '
+
COMMASPACE = ', '
 
+
 
+
def main():
+
def main():
    parser = OptionParser(usage="""\
+
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.
+
Send the contents of a directory as a MIME message.
 
+
Usage: %prog [options]
+
Usage: %prog [options]  
 
+
Unless the -o option is given, the email is sent by forwarding to your local
+
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
+
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
+
must be running an SMTP server.
""")
+
""")
    parser.add_option('-d', '--directory',
+
    parser.add_option('-d', '--directory',
                      type='string', action='store',
+
                      type='string', action='store',
                      help="""Mail the contents of the specified directory,
+
                      help="""Mail the contents of the specified directory,
                      otherwise use the current directory.  Only the regular
+
                      otherwise use the current directory.  Only the regular
                      files in the directory are sent, and we don't recurse to
+
                      files in the directory are sent, and we don't recurse to
                      subdirectories.""")
+
                      subdirectories.""")
    parser.add_option('-o', '--output',
+
    parser.add_option('-o', '--output',
                      type='string', action='store', metavar='FILE',
+
                      type='string', action='store', metavar='FILE',
                      help="""Print the composed message to FILE instead of
+
                      help="""Print the composed message to FILE instead of
                      sending the message to the SMTP server.""")
+
                      sending the message to the SMTP server.""")
    parser.add_option('-s', '--sender',
+
    parser.add_option('-s', '--sender',
                      type='string', action='store', metavar='SENDER',
+
                      type='string', action='store', metavar='SENDER',
                      help='The value of the From: header (required)')
+
                      help='The value of the From: header (required)')
    parser.add_option('-r', '--recipient',
+
    parser.add_option('-r', '--recipient',
                      type='string', action='append', metavar='RECIPIENT',
+
                      type='string', action='append', metavar='RECIPIENT',
                      default=[], dest='recipients',
+
                      default=[], dest='recipients',
                      help='A To: header value (at least one required)')
+
                      help='A To: header value (at least one required)')
    opts, args = parser.parse_args()
+
    opts, args = parser.parse_args()
    if not opts.sender or not opts.recipients:
+
    if not opts.sender or not opts.recipients:
        parser.print_help()
+
        parser.print_help()
        sys.exit(1)
+
        sys.exit(1)
    directory = opts.directory
+
    directory = opts.directory
    if not directory:
+
    if not directory:
        directory = '.'
+
        directory = '.'
    # Create the enclosing (outer) message
+
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
+
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
+
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    outer['To'] = COMMASPACE.join(opts.recipients)
+
    outer['To'] = COMMASPACE.join(opts.recipients)
    outer['From'] = opts.sender
+
    outer['From'] = opts.sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
+
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'  
 
+
    for filename in os.listdir(directory):
+
    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
+
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
+
        if not os.path.isfile(path):
            continue
+
            continue
        # Guess the content type based on the file's extension.  Encoding
+
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
+
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
+
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
+
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
+
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
+
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
+
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
+
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
+
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
+
        if maintype == 'text':
            fp = open(path)
+
            fp = open(path)
            # Note: we should handle calculating the charset
+
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
+
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
+
            fp.close()
        elif maintype == 'image':
+
        elif maintype == 'image':
            fp = open(path, 'rb')
+
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
+
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
+
            fp.close()
        elif maintype == 'audio':
+
        elif maintype == 'audio':
            fp = open(path, 'rb')
+
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
+
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
+
            fp.close()
        else:
+
        else:
            fp = open(path, 'rb')
+
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
+
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
+
            msg.set_payload(fp.read())
            fp.close()
+
            fp.close()
            # Encode the payload using Base64
+
            # Encode the payload using Base64
            encoders.encode_base64(msg)
+
            encoders.encode_base64(msg)
        # Set the filename parameter
+
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
+
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)
+
        outer.attach(msg)
    # Now send or store the message
+
    # Now send or store the message
    composed = outer.as_string()
+
    composed = outer.as_string()
    if opts.output:
+
    if opts.output:
        fp = open(opts.output, 'w')
+
        fp = open(opts.output, 'w')
        fp.write(composed)
+
        fp.write(composed)
        fp.close()
+
        fp.close()
    else:
+
    else:
        s = smtplib.SMTP('localhost')
+
        s = smtplib.SMTP('localhost')
        s.sendmail(opts.sender, opts.recipients, composed)
+
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()
+
        s.quit()
 
+
 
 
+
if __name__ == '__main__':
+
if __name__ == '__main__':
    main()
+
    main()
  
 
Here’s an example of how to unpack a MIME message like the one above, into a directory of files:
 
Here’s an example of how to unpack a MIME message like the one above, into a directory of files:
  
#!/usr/bin/env python
+
#!/usr/bin/env python
 
+
"""Unpack a MIME message into a directory of files."""
+
"""Unpack a MIME message into a directory of files."""
 
+
import os
+
import os
import sys
+
import sys
import email
+
import email
import errno
+
import errno
import mimetypes
+
import mimetypes
 
+
from optparse import OptionParser
+
from optparse import OptionParser  
 
+
 
 
+
def main():
+
def main():
    parser = OptionParser(usage="""\
+
    parser = OptionParser(usage="""\
Unpack a MIME message into a directory of files.
+
Unpack a MIME message into a directory of files.
 
+
Usage: %prog [options] msgfile
+
Usage: %prog [options] msgfile
""")
+
""")
    parser.add_option('-d', '--directory',
+
    parser.add_option('-d', '--directory',
                      type='string', action='store',
+
                      type='string', action='store',
                      help="""Unpack the MIME message into the named
+
                      help="""Unpack the MIME message into the named
                      directory, which will be created if it doesn't already
+
                      directory, which will be created if it doesn't already
                      exist.""")
+
                      exist.""")
    opts, args = parser.parse_args()
+
    opts, args = parser.parse_args()
    if not opts.directory:
+
    if not opts.directory:
        parser.print_help()
+
        parser.print_help()
        sys.exit(1)
+
        sys.exit(1)  
 
+
    try:
+
    try:
        msgfile = args[0]
+
        msgfile = args[0]
    except IndexError:
+
    except IndexError:
        parser.print_help()
+
        parser.print_help()
        sys.exit(1)
+
        sys.exit(1)
 
+
    try:
+
    try:
        os.mkdir(opts.directory)
+
        os.mkdir(opts.directory)
    except OSError as e:
+
    except OSError as e:
        # Ignore directory exists error
+
        # Ignore directory exists error
        if e.errno != errno.EEXIST:
+
        if e.errno != errno.EEXIST:
            raise
+
            raise  
 
+
    fp = open(msgfile)
+
    fp = open(msgfile)
    msg = email.message_from_file(fp)
+
    msg = email.message_from_file(fp)
    fp.close()
+
    fp.close()  
 
+
    counter = 1
+
    counter = 1
    for part in msg.walk():
+
    for part in msg.walk():
        # multipart/* are just containers
+
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
+
        if part.get_content_maintype() == 'multipart':
            continue
+
            continue
        # Applications should really sanitize the given filename so that an
+
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
+
        # email message can't be used to overwrite important files
        filename = part.get_filename()
+
        filename = part.get_filename()
        if not filename:
+
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
+
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
+
            if not ext:
                # Use a generic bag-of-bits extension
+
                # Use a generic bag-of-bits extension
                ext = '.bin'
+
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
+
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
+
        counter += 1
        fp = open(os.path.join(opts.directory, filename), 'wb')
+
        fp = open(os.path.join(opts.directory, filename), 'wb')
        fp.write(part.get_payload(decode=True))
+
        fp.write(part.get_payload(decode=True))
        fp.close()
+
        fp.close()  
 
+
 
+
if __name__ == '__main__':
+
if __name__ == '__main__':
    main()
+
    main()
  
 
Here’s an example of how to create an HTML message with an alternative plain text version: [2]
 
Here’s an example of how to create an HTML message with an alternative plain text version: [2]

Latest revision as of 09:28, 3 December 2015

Sumber: https://docs.python.org/2/library/email-examples.html


Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.

First, let’s see how to create and send a simple text message:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

And parsing RFC822 headers can easily be done by the parse(filename) or parsestr(message_as_string) methods of the Parser() class:

# Import the email modules we'll need
from email.parser import Parser

#  If the e-mail headers are in a file, uncomment this line:
#headers = Parser().parse(open(messagefile, 'r')) 

#  Or for parsing headers in a string, use:
headers = Parser().parsestr('From: <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n') 

#  Now the header items can be accessed as a dictionary:
print 'To: %s' % headers['to']
print 'From: %s' % headers['from']
print 'Subject: %s' % headers['subject']

Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img) 

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

Here’s an example of how to send the entire contents of a directory as an email message: [1]

#!/usr/bin/env python

"""Send the contents of a directory as a MIME message.""" 

import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '


def main():
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options] 

Unless the -o option is given, 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.
""")
    parser.add_option('-d', '--directory',
                      type='string', action='store',
                      help="""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.""")
    parser.add_option('-o', '--output',
                      type='string', action='store', metavar='FILE',
                      help="""Print the composed message to FILE instead of
                      sending the message to the SMTP server.""")
    parser.add_option('-s', '--sender',
                      type='string', action='store', metavar='SENDER',
                      help='The value of the From: header (required)')
    parser.add_option('-r', '--recipient',
                      type='string', action='append', metavar='RECIPIENT',
                      default=[], dest='recipients',
                      help='A To: header value (at least one required)')
    opts, args = parser.parse_args()
    if not opts.sender or not opts.recipients:
        parser.print_help()
        sys.exit(1)
    directory = opts.directory
    if not directory:
        directory = '.'
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    outer['To'] = COMMASPACE.join(opts.recipients)
    outer['From'] = opts.sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' 

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # 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)
        if maintype == 'text':
            fp = open(path)
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)
    # Now send or store the message
    composed = outer.as_string()
    if opts.output:
        fp = open(opts.output, 'w')
        fp.write(composed)
        fp.close()
    else:
        s = smtplib.SMTP('localhost')
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()
 

if __name__ == '__main__':
    main()

Here’s an example of how to unpack a MIME message like the one above, into a directory of files:

#!/usr/bin/env python

"""Unpack a MIME message into a directory of files."""

import os
import sys
import email
import errno
import mimetypes

from optparse import OptionParser 
 

def main():
    parser = OptionParser(usage="""\
Unpack a MIME message into a directory of files.

Usage: %prog [options] msgfile
""")
    parser.add_option('-d', '--directory',
                      type='string', action='store',
                      help="""Unpack the MIME message into the named
                      directory, which will be created if it doesn't already
                      exist.""")
    opts, args = parser.parse_args()
    if not opts.directory:
        parser.print_help()
        sys.exit(1) 

    try:
        msgfile = args[0]
    except IndexError:
        parser.print_help()
        sys.exit(1)

    try:
        os.mkdir(opts.directory)
    except OSError as e:
        # Ignore directory exists error
        if e.errno != errno.EEXIST:
            raise 

    fp = open(msgfile)
    msg = email.message_from_file(fp)
    fp.close() 

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        fp = open(os.path.join(opts.directory, filename), 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close() 


if __name__ == '__main__':
    main()

Here’s an example of how to create an HTML message with an alternative plain text version: [2]

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = """\
<html>
  <head></head>
  <body>

Hi!
How are you?
Here is the <a href="https://www.python.org">link</a> you wanted.

  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)  

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

Footnotes [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples. [2] Contributed by Martin Matejek.



Referensi