可以使用SMTP(Simple Mail Transfer Protocol)来发送邮件,使用POP3(Post Office Protocol version 3)或IMAP(Internet Message Access Protocol)来接收邮件。 以下是一个基本的Python示例,使用SMTP库来发送电子邮件:
import smtplib
sender_email = "sender@example.com"
receiver_email = "receiver@example.com"
password = "password123"
message = """\
Subject: Hi there
This is an email sent from Python."""
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
在上面的示例中,我们使用Gmail SMTP服务器发送一封电子邮件。请注意,您需要在此之前启用Gmail的“安全应用程序访问权限”。 对于接收电子邮件,您可以使用Python内置的imaplib库和poplib库。以下是一个示例:
import imaplib
username = "user@example.com"
password = "password123"
mail = imaplib.IMAP4_SSL("imap.example.com")
mail.login(username, password)
mail.select("INBOX")
status, messages = mail.search(None, "ALL")
messages = messages[0].split(b' ')
for msg in messages:
_, msg_data = mail.fetch(msg, "(RFC822)")
print(msg_data[0][1])
mail.close()
mail.logout()
在上面的示例中,我们使用IMAP4协议从一个名为“INBOX”的文件夹中检索所有电子邮件。请注意,您需要将“imap.example.com”替换为实际的IMAP服务器地址,并使用正确的用户名和密码进行身份验证。