用PYTHON实现一个邮件客户工具端类,可以接收邮件,可以发送邮件,可以删除邮件,可以获取未阅读邮件
时间: 2023-02-05 15:57:08 浏览: 102
好的,这是一个使用 Python 实现的邮件客户端类的示例:
```
import imaplib
import smtplib
class EmailClient:
def __init__(self, email, password):
self.email = email
self.password = password
def send_email(self, to, subject, body):
# 创建 SMTP 连接
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(self.email, self.password)
# 构建邮件内容
message = f"Subject: {subject}\n\n{body}"
# 发送邮件
server.sendmail(self.email, to, message)
server.quit()
def receive_emails(self):
# 创建 IMAP 连接
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(self.email, self.password)
# 获取邮件列表
mail.select("inbox")
result, data = mail.search(None, "ALL")
# 遍历邮件并输出标题和内容
for num in data[0].split():
result, data = mail.fetch(num, "(RFC822)")
msg = email.message_from_bytes(data[0][1])
print(f'Subject: {msg["Subject"]}')
print(f'From: {msg["From"]}')
print(f'Date: {msg["Date"]}')
print(msg.get_payload())
# 关闭连接
mail.close()
mail.logout()
def delete_email(self, email_id):
# 创建 IMAP 连接
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(self.email, self.password)
# 将邮件标记为删除
mail.select("inbox")
mail.store(email_id, '+FLAGS', '\\Deleted')
# 永久删除邮件
mail.expunge()
# 关闭连接
mail.close()
mail.logout()
def get_unread_emails(self):
# 创建 IMAP 连接
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(self.email, self.password)
# 获取未读邮件列表
mail
阅读全文