19.1.8. email: 示例

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

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

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

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

    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. parser.add_argument('-s', '--sender', required=True,
    26. help='The value of the From: header (required)')
    27. parser.add_argument('-r', '--recipient', required=True,
    28. action='append', metavar='RECIPIENT',
    29. default=[], dest='recipients',
    30. help='A To: header value (at least one required)')
    31. args = parser.parse_args()
    32. directory = args.directory
    33. if not directory:
    34. directory = '.'
    35. # Create the message
    36. msg = EmailMessage()
    37. msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    38. msg['To'] = ', '.join(args.recipients)
    39. msg['From'] = args.sender
    40. msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    41. for filename in os.listdir(directory):
    42. path = os.path.join(directory, filename)
    43. if not os.path.isfile(path):
    44. continue
    45. # Guess the content type based on the file's extension. Encoding
    46. # will be ignored, although we should check for simple things like
    47. # gzip'd or compressed files.
    48. ctype, encoding = mimetypes.guess_type(path)
    49. if ctype is None or encoding is not None:
    50. # No guess could be made, or the file is encoded (compressed), so
    51. # use a generic bag-of-bits type.
    52. ctype = 'application/octet-stream'
    53. maintype, subtype = ctype.split('/', 1)
    54. with open(path, 'rb') as fp:
    55. msg.add_attachment(fp.read(),
    56. maintype=maintype,
    57. subtype=subtype,
    58. filename=filename)
    59. # Now send or store the message
    60. if args.output:
    61. with open(args.output, 'wb') as fp:
    62. fp.write(msg.as_bytes(policy=SMTP))
    63. else:
    64. with smtplib.SMTP('localhost') as s:
    65. s.send_message(msg)
    66. if __name__ == '__main__':
    67. main()

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

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

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

    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.

    备注

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