实现一个邮件工具类,可以本地邮件发送和邮件接受功能

本文提供了一个Python邮件发送和接收的示例。`Mailer`类用于发送邮件,通过SMTP服务器,输入主机、端口、用户名和密码即可。而`MailReceiver`类则用于接收邮件,使用IMAP4协议,同样需要服务器信息和认证凭证。这两个类为基本的邮件操作提供了便利。
摘要由CSDN通过智能技术生成

好的,下面是一个简单的邮件工具类的例子:

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 方法,可以用来接收邮件。像发送邮

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值