用PYTHON实现一个邮件类,可以接收邮件,可以发送邮件,可以删除邮件,可以获取未阅读邮件,可以给邮件做标记
时间: 2023-02-05 19:47:00 浏览: 103
python邮件接收发送【完整脚本】
5星 · 资源好评率100%
这是一个使用 Python 实现的简单的邮件类的示例:
```
import smtplib
import imaplib
class Email:
def __init__(self, username, password):
self.username = username
self.password = password
def send_email(self, to, subject, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(self.username, self.password)
server.sendmail(self.username, to, f'Subject: {subject}\n\n{message}')
server.close()
def receive_email(self):
mailbox = imaplib.IMAP4_SSL('imap.gmail.com')
mailbox.login(self.username, self.password)
mailbox.select()
_, search_results = mailbox.search(None, 'UNSEEN')
if search_results[0]:
for email_id in search_results[0].split():
_, msg = mailbox.fetch(email_id, "(RFC822)")
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
subject = msg['subject']
sender = msg['from']
print(f'Subject: {subject}\nFrom: {sender}\n')
mailbox.close()
mailbox.logout()
def delete_email(self, email_id):
mailbox = imaplib.IMAP4_SSL('imap.gmail.com')
mailbox.login(self.username, self.password)
mailbox.select()
mailbox.store(email_id, '+FLAGS', '\\Deleted')
mailbox.expunge()
mailbox.close()
mailbox.logout()
def mark_as_read(self, email_id):
mailbox = imaplib.IMAP4_SSL('imap.gmail.com')
mailbox.login(self.username, self.password)
mailbox.select()
mailbox.store(email_id, '+FLAGS', '\\Seen')
mailbox.close()
mailbox.logout()
```
该类实现了五个功能:
1. `send_email` 函数用于发送邮件,接收三个参数:收件人地址、主题和消息正文。
2. `receive_email` 函数用于接收未读邮件,并在控制台输出主题和发件人信息。
3. `delete_email` 函数用于
阅读全文