用PYTHON实现一个工具类,可以接收邮件,可以发送邮件,可以删除邮件,可以给邮件做标记
时间: 2023-02-18 09:58:29 浏览: 64
你可以使用 Python 的 `imaplib` 模块和 `smtplib` 模块来实现这些功能。
下面是一个示例代码,实现了接收、发送、删除和标记邮件的功能:
```python
import imaplib
import smtplib
import email
class EmailClient:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def connect(self):
self.imap_client = imaplib.IMAP4_SSL(self.host)
self.imap_client.login(self.username, self.password)
def disconnect(self):
self.imap_client.close()
self.imap_client.logout()
def send_email(self, to, subject, body):
message = f"""\
From: {self.username}
To: {to}
Subject: {subject}
{body}
"""
smtp_client = smtplib.SMTP_SSL(self.host)
smtp_client.login(self.username, self.password)
smtp_client.sendmail(self.username, to, message)
smtp_client.quit()
def fetch_unread_emails(self):
self.imap_client.select('INBOX')
_, msg_ids = self.imap_client.search(None, 'UNSEEN')
msg_ids = msg_ids[0].split()
return [self._fetch_email(msg_id) for msg_id in msg_ids]
def _fetch_email(self, msg_id):
_, msg_data = self.imap_client.fetch(msg_id, "(RFC822)")
msg = email.message_from_bytes(msg_data[0][1])
return {
'subject': msg['subject'],
'from': msg['from'],
'to': msg['to'],
'body': msg.get_payload()
}
def delete_email(self, msg_id):
self.imap_client.store(msg_id, '+FLAGS', '\\Deleted')
self.imap_client.expunge()
def mark_as_read(self, msg_id):
self.imap_client.store(msg_id, '+FLAGS', '\\Seen')
# 使用方法示例
email_client = EmailClient("imap.example.com", "username", "password")
email_client.connect()
# 发送邮件
email_client.send_email("to@example.com", "Subject", "Body")
# 获取未读邮件