好的,下面是一个简单的邮件工具类的例子:
import smtplib
from email.mime.text import MIMEText
class Mailer:
def __init__(self, host, port, username, password):
self.host = host
self.port = port
self.username = username
self.password = password
def send(self, to, subject, message):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = self.username
msg['To'] = to
with smtplib.SMTP(self.host, self.port) as smtp:
smtp.login(self.username, self.password)
smtp.send_message(msg)
mailer = Mailer('smtp.example.com', 587, 'user@example.com', 'password')
mailer.send('recipient@example.com', 'Subject', 'Message')
这个类提供了一个 send
方法,可以用来发送邮件。在构造函数中,你需要提供 SMTP 服务器的地址、端口、用户名和密码。然后,你就可以使用 send
方法发送邮件了。
如果你想实现邮件接收功能,你可以使用 Python 的 imaplib
库。下面是一个例子:
import imaplib
class MailReceiver:
def __init__(self, host, port, username, password):
self.host = host
self.port = port
self.username = username
self.password = password
def receive(self):
with imaplib.IMAP4(self.host, self.port) as imap:
imap.login(self.username, self.password)
imap.select()
_, messages = imap.search(None, 'ALL')
for message in messages[0].split():
_, msg = imap.fetch(message, '(RFC822)')
yield msg[0][1]
receiver = MailReceiver('imap.example.com', 993, 'user@example.com', 'password')
for message in receiver.receive():
print(message)
这个类提供了一个 receive
方法,可以用来接收邮件。像发送邮