email: 示例

以下是一些如何使用 email 包来读取、写入和发送简单电子邮件以及更复杂的MIME邮件的示例。

首先,让我们看看如何创建和发送简单的文本消息(文本内容和地址都可能包含unicode字符):

  1. # Import smtplib for the actual sending function
  2. import smtplib
  3. # Import the email modules we'll need
  4. from email.message import EmailMessage
  5. # Open the plain text file whose name is in textfile for reading.
  6. with open(textfile) as fp:
  7. # Create a text/plain message
  8. msg = EmailMessage()
  9. msg.set_content(fp.read())
  10. # me == the sender's email address
  11. # you == the recipient's email address
  12. msg['Subject'] = f'The contents of {textfile}'
  13. msg['From'] = me
  14. msg['To'] = you
  15. # Send the message via our own SMTP server.
  16. s = smtplib.SMTP('localhost')
  17. s.send_message(msg)
  18. s.quit()

解析 RFC 822 标题可以通过使用 parser 模块中的类来轻松完成:

  1. # Import the email modules we'll need
  2. from email.parser import BytesParser, Parser
  3. from email.policy import default
  4. # If the e-mail headers are in a file, uncomment these two lines:
  5. # with open(messagefile, 'rb') as fp:
  6. # headers = BytesParser(policy=default).parse(fp)
  7. # Or for parsing headers in a string (this is an uncommon operation), use:
  8. headers = Parser(policy=default).parsestr(
  9. 'From: Foo Bar <user@example.com>\n'
  10. 'To: <someone_else@example.com>\n'
  11. 'Subject: Test message\n'
  12. '\n'
  13. 'Body would go here\n')
  14. # Now the header items can be accessed as a dictionary:
  15. print('To: {}'.format(headers['to']))
  16. print('From: {}'.format(headers['from']))
  17. print('Subject: {}'.format(headers['subject']))
  18. # You can also access the parts of the addresses:
  19. print('Recipient username: {}'.format(headers['to'].addresses[0].username))
  20. print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

以下是如何发送包含可能在目录中的一系列家庭照片的MIME消息示例:

  1. # Import smtplib for the actual sending function.
  2. import smtplib
  3. # Here are the email package modules we'll need.
  4. from email.message import EmailMessage
  5. # Create the container email message.
  6. msg = EmailMessage()
  7. msg['Subject'] = 'Our family reunion'
  8. # me == the sender's email address
  9. # family = the list of all recipients' email addresses
  10. msg['From'] = me
  11. msg['To'] = ', '.join(family)
  12. msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
  13. # Open the files in binary mode. You can also omit the subtype
  14. # if you want MIMEImage to guess it.
  15. for file in pngfiles:
  16. with open(file, 'rb') as fp:
  17. img_data = fp.read()
  18. msg.add_attachment(img_data, maintype='image',
  19. subtype='png')
  20. # Send the email via our own SMTP server.
  21. with smtplib.SMTP('localhost') as s:
  22. s.send_message(msg)

以下是如何将目录的全部内容作为电子邮件消息发送的示例: 1

  1. #!/usr/bin/env python3
  2. """Send the contents of a directory as a MIME message."""
  3. import os
  4. import smtplib
  5. # For guessing MIME type based on file name extension
  6. import mimetypes
  7. from argparse import ArgumentParser
  8. from email.message import EmailMessage
  9. from email.policy import SMTP
  10. def main():
  11. parser = ArgumentParser(description="""\
  12. Send the contents of a directory as a MIME message.
  13. Unless the -o option is given, the email is sent by forwarding to your local
  14. SMTP server, which then does the normal delivery process. Your local machine
  15. must be running an SMTP server.
  16. """)
  17. parser.add_argument('-d', '--directory',
  18. help="""Mail the contents of the specified directory,
  19. otherwise use the current directory. Only the regular
  20. files in the directory are sent, and we don't recurse to
  21. subdirectories.""")
  22. parser.add_argument('-o', '--output',
  23. metavar='FILE',
  24. help="""Print the composed message to FILE instead of
  25. sending the message to the SMTP server.""")
  26. parser.add_argument('-s', '--sender', required=True,
  27. help='The value of the From: header (required)')
  28. parser.add_argument('-r', '--recipient', required=True,
  29. action='append', metavar='RECIPIENT',
  30. default=[], dest='recipients',
  31. help='A To: header value (at least one required)')
  32. args = parser.parse_args()
  33. directory = args.directory
  34. if not directory:
  35. directory = '.'
  36. # Create the message
  37. msg = EmailMessage()
  38. msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'
  39. msg['To'] = ', '.join(args.recipients)
  40. msg['From'] = args.sender
  41. msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
  42. for filename in os.listdir(directory):
  43. path = os.path.join(directory, filename)
  44. if not os.path.isfile(path):
  45. continue
  46. # Guess the content type based on the file's extension. Encoding
  47. # will be ignored, although we should check for simple things like
  48. # gzip'd or compressed files.
  49. ctype, encoding = mimetypes.guess_type(path)
  50. if ctype is None or encoding is not None:
  51. # No guess could be made, or the file is encoded (compressed), so
  52. # use a generic bag-of-bits type.
  53. ctype = 'application/octet-stream'
  54. maintype, subtype = ctype.split('/', 1)
  55. with open(path, 'rb') as fp:
  56. msg.add_attachment(fp.read(),
  57. maintype=maintype,
  58. subtype=subtype,
  59. filename=filename)
  60. # Now send or store the message
  61. if args.output:
  62. with open(args.output, 'wb') as fp:
  63. fp.write(msg.as_bytes(policy=SMTP))
  64. else:
  65. with smtplib.SMTP('localhost') as s:
  66. s.send_message(msg)
  67. if __name__ == '__main__':
  68. main()

以下是如何将上述MIME消息解压缩到文件目录中的示例:

  1. #!/usr/bin/env python3
  2. """Unpack a MIME message into a directory of files."""
  3. import os
  4. import email
  5. import mimetypes
  6. from email.policy import default
  7. from argparse import ArgumentParser
  8. def main():
  9. parser = ArgumentParser(description="""\
  10. Unpack a MIME message into a directory of files.
  11. """)
  12. parser.add_argument('-d', '--directory', required=True,
  13. help="""Unpack the MIME message into the named
  14. directory, which will be created if it doesn't already
  15. exist.""")
  16. parser.add_argument('msgfile')
  17. args = parser.parse_args()
  18. with open(args.msgfile, 'rb') as fp:
  19. msg = email.message_from_binary_file(fp, policy=default)
  20. try:
  21. os.mkdir(args.directory)
  22. except FileExistsError:
  23. pass
  24. counter = 1
  25. for part in msg.walk():
  26. # multipart/* are just containers
  27. if part.get_content_maintype() == 'multipart':
  28. continue
  29. # Applications should really sanitize the given filename so that an
  30. # email message can't be used to overwrite important files
  31. filename = part.get_filename()
  32. if not filename:
  33. ext = mimetypes.guess_extension(part.get_content_type())
  34. if not ext:
  35. # Use a generic bag-of-bits extension
  36. ext = '.bin'
  37. filename = f'part-{counter:03d}{ext}'
  38. counter += 1
  39. with open(os.path.join(args.directory, filename), 'wb') as fp:
  40. fp.write(part.get_payload(decode=True))
  41. if __name__ == '__main__':
  42. main()

以下是如何使用备用纯文本版本创建 HTML 消息的示例。 为了让事情变得更有趣,我们在 html 部分中包含了一个相关的图像,我们保存了一份我们要发送的内容到硬盘中,然后发送它。

  1. #!/usr/bin/env python3
  2. import smtplib
  3. from email.message import EmailMessage
  4. from email.headerregistry import Address
  5. from email.utils import make_msgid
  6. # Create the base text message.
  7. msg = EmailMessage()
  8. msg['Subject'] = "Ayons asperges pour le déjeuner"
  9. msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
  10. msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
  11. Address("Fabrette Pussycat", "fabrette", "example.com"))
  12. msg.set_content("""\
  13. Salut!
  14. Cela ressemble à un excellent recipie[1] déjeuner.
  15. [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
  16. --Pepé
  17. """)
  18. # Add the html version. This converts the message into a multipart/alternative
  19. # container, with the original text message as the first part and the new html
  20. # message as the second part.
  21. asparagus_cid = make_msgid()
  22. msg.add_alternative("""\
  23. <html>
  24. <head></head>
  25. <body>
  26. <p>Salut!</p>
  27. <p>Cela ressemble à un excellent
  28. <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
  29. recipie
  30. </a> déjeuner.
  31. </p>
  32. <img src="cid:{asparagus_cid}" />
  33. </body>
  34. </html>
  35. """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
  36. # note that we needed to peel the <> off the msgid for use in the html.
  37. # Now add the related image to the html part.
  38. with open("roasted-asparagus.jpg", 'rb') as img:
  39. msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
  40. cid=asparagus_cid)
  41. # Make a local copy of what we are going to send.
  42. with open('outgoing.msg', 'wb') as f:
  43. f.write(bytes(msg))
  44. # Send the message via local SMTP server.
  45. with smtplib.SMTP('localhost') as s:
  46. s.send_message(msg)

如果我们发送最后一个示例中的消息,这是我们可以处理它的一种方法:

  1. import os
  2. import sys
  3. import tempfile
  4. import mimetypes
  5. import webbrowser
  6. # Import the email modules we'll need
  7. from email import policy
  8. from email.parser import BytesParser
  9. def magic_html_parser(html_text, partfiles):
  10. """Return safety-sanitized html linked to partfiles.
  11. Rewrite the href="cid:...." attributes to point to the filenames in partfiles.
  12. Though not trivial, this should be possible using html.parser.
  13. """
  14. raise NotImplementedError("Add the magic needed")
  15. # In a real program you'd get the filename from the arguments.
  16. with open('outgoing.msg', 'rb') as fp:
  17. msg = BytesParser(policy=policy.default).parse(fp)
  18. # Now the header items can be accessed as a dictionary, and any non-ASCII will
  19. # be converted to unicode:
  20. print('To:', msg['to'])
  21. print('From:', msg['from'])
  22. print('Subject:', msg['subject'])
  23. # If we want to print a preview of the message content, we can extract whatever
  24. # the least formatted payload is and print the first three lines. Of course,
  25. # if the message has no plain text part printing the first three lines of html
  26. # is probably useless, but this is just a conceptual example.
  27. simplest = msg.get_body(preferencelist=('plain', 'html'))
  28. print()
  29. print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))
  30. ans = input("View full message?")
  31. if ans.lower()[0] == 'n':
  32. sys.exit()
  33. # We can extract the richest alternative in order to display it:
  34. richest = msg.get_body()
  35. partfiles = {}
  36. if richest['content-type'].maintype == 'text':
  37. if richest['content-type'].subtype == 'plain':
  38. for line in richest.get_content().splitlines():
  39. print(line)
  40. sys.exit()
  41. elif richest['content-type'].subtype == 'html':
  42. body = richest
  43. else:
  44. print("Don't know how to display {}".format(richest.get_content_type()))
  45. sys.exit()
  46. elif richest['content-type'].content_type == 'multipart/related':
  47. body = richest.get_body(preferencelist=('html'))
  48. for part in richest.iter_attachments():
  49. fn = part.get_filename()
  50. if fn:
  51. extension = os.path.splitext(part.get_filename())[1]
  52. else:
  53. extension = mimetypes.guess_extension(part.get_content_type())
  54. with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
  55. f.write(part.get_content())
  56. # again strip the <> to go from email form of cid to html form.
  57. partfiles[part['content-id'][1:-1]] = f.name
  58. else:
  59. print("Don't know how to display {}".format(richest.get_content_type()))
  60. sys.exit()
  61. with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
  62. f.write(magic_html_parser(body.get_content(), partfiles))
  63. webbrowser.open(f.name)
  64. os.remove(f.name)
  65. for fn in partfiles.values():
  66. os.remove(fn)
  67. # Of course, there are lots of email messages that could break this simple
  68. # minded program, but it will handle the most common ones.

直到输出提示,上面的输出是:

  1. To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
  2. From: Pepé Le Pew <pepe@example.com>
  3. Subject: Ayons asperges pour le déjeuner
  4. Salut!
  5. Cela ressemble à un excellent recipie[1] déjeuner.

备注

1

感谢 Matthew Dixon Cowles 提供最初的灵感和示例。