有许多模块可用于访问互联网和处理互联网协议。其中两个最简单的 urllib.request 用于从URL检索数据,以及 smtplib 用于发送邮件:
>>>
from urllib.request import urlopen
with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
for line in response:
line = line.decode() # Convert bytes to a str
if line.startswith('datetime'):
print(line.rstrip()) # Remove trailing newline
datetime: 2022-01-01T01:36:47.689215+00:00
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
server.quit()
(请注意,第二个示例需要在localhost上运行的邮件服务器。)
|