python 收发邮件

本文介绍了使用Python的poplib和smtp模块实现邮件的接收和发送。首先,讲解了准备工作,包括开启新浪邮箱的POP3/SMTP服务。接着,详细阐述了如何利用poplib登录邮箱并获取邮件信息。然后,展示了通过smtp发送邮件的步骤。最后,提供了源码和测试结果,鼓励读者亲自尝试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天记录一下如何使用python收发邮件,知识要点在python内置的poplib和stmplib模块的使用上。

1. 准备工作

首先,我们需要有一个测试邮箱,我们使用新浪邮箱,而且要进行如下设置:

在新浪邮箱首页的右上角找到设置->更多设置,然后在左边选择“客户端/pop/imap/smtp”:

最后,将Pop3/smtp服务的服务状态打开即可:

2. poplib接收邮件

首先,介绍一下poplib登录邮箱和下载邮件的一些接口:

        self.popHost = 'pop.sina.com'
        self.smtpHost = 'smtp.sina.com'
        self.port = 25
        self.userName = 'xxxxxx@sina.com'
        self.passWord = 'xxxxxx'
        self.bossMail = 'xxxxxx@qq.com'

我们需要如上一些常量,用于指定登录邮箱以及pop,smtp服务器及端口。我们调用poplib的POP3_SSL接口可以登录到邮箱。

    # 登录邮箱
    def login(self):
        try:
            self.mailLink = poplib.POP3_SSL(self.popHost)
            self.mailLink.set_debuglevel(0)
            self.mailLink.user(self.userName)
            self.mailLink.pass_(self.passWord)
            self.mailLink.list()
            print u'login success!'
        except Exception as e:
            print u'login fail! ' + str(e)
            quit()

在登录邮箱的时候,很自然,我们需要提供用户名和密码,如上述代码所示,使用非常简单。

登录邮箱成功后,我们可以使用list方法获取邮箱的邮件信息。我们看到list方法的定义:

### 使用Python实现邮件发送 为了利用Python进行邮件的发送操作,通常会采用`smtplib`库来构建SMTP客户端会话对象,这使得可以连接到服务器并登录邮箱账户从而完成邮件的发送工作[^1]。 下面是一个简单的例子展示怎样使用Python编写程序向指定地址发送一封纯文本电子邮件: ```python import smtplib from email.mime.text import MIMEText from email.header import Header sender = 'your_email@example.com' receivers = ['receiver_email@example.com'] # 接收者列表 message = MIMEText('这是测试邮件的内容', 'plain', 'utf-8') message['From'] = Header("发件人姓名", 'utf-8') message['To'] = Header("收件人姓名", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL('smtp.example.com', 465) # 创建SMTP对象,这里指定了SSL模式 smtpObj.login(sender, "password") # 登录到你自己的邮箱账号 smtpObj.sendmail(sender, receivers, message.as_string()) # 发送邮件 print ("邮件发送成功") except Exception as e: print (f"Error: {e}") finally: smtpObj.quit() ``` 这段代码展示了基本的设置过程以及异常处理机制以确保即使发生错误也能正常关闭与SMTP服务器之间的连接。 对于更复杂的需求比如HTML格式邮件或是带有附件的情况,则需要引入其他MIME类型的支持,并调整相应的编码方式。 --- ### 使用Python实现邮件接收 当涉及到通过Python读取或下载已收到的邮件时,一般会选择IMAP协议而不是POP3因为前者允许用户在不删除原始消息的情况下查看远程邮箱中的内容。为此目的服务的一个流行第三方库叫做`imaplib`. 以下是获取最新未读邮件主题的一段示范脚本: ```python import imaplib import email from email.header import decode_header def fetch_unread_emails(email_user, password): mail = imaplib.IMAP4_SSL('imap.example.com') mail.login(email_user,password) status, messages = mail.select('INBOX') response_code, data = mail.search(None,'UNSEEN') unread_msg_nums = data[0].split() latest_unread_subjects = [] for num in unread_msg_nums[-1:-6:-1]: typ, msg_data = mail.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1]) subject, encoding = decode_header(msg["Subject"])[0] if isinstance(subject, bytes): try: subject = subject.decode(encoding or 'utf-8') except UnicodeDecodeError: continue latest_unread_subjects.append(subject) fetch_unread_emails('your_email@example.com','password') print(latest_unread_subjects) ``` 此函数将返回最近五封未阅读过的电邮的主题行作为字符串数组输出.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值