python: smtp/pop/imap

本文介绍如何使用Python的smtplib和poplib模块实现邮件的发送与接收功能。通过具体的代码示例,展示了如何利用SMTP协议发送邮件及利用POP3协议接收邮件的过程。

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

邮件的服务器MTA:smtp协议

邮件的客户端MUA: pop3协议,imap协议。


###############################################

python使用smtplib模块编写邮件服务器程序。


SMTP类:

__init__(self, host='', port=0, local_hostname=None, timeout=<object object>)


smtplib.SMTP类的方法:

connect(host='localhost', port=0)

sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]):

to_addrs是一个地址列表,msg的From: To: Subject:能自动识别

sendmail返回没有发出的邮件和错误信息的字典{email,message}

quit()


################################################

python的邮件客户端模块有poplib和imaplib两种


POP3类:

__init__(self, host, port=110, timeout=<object object>)


POP3类的方法:

user(username)

pass_(password)

stat()-> 获取消息的数量和消息总大小,返回(message count, mailbox size)

list(which=None) -> 

如果没有给出which返回,['response', ['mesg_num octets', ...], octets]

如果给出which只返回response

retr(which)-> 获取which的服务器返回信息、消息的所有行、消息的字节,返回['response', ['line', ...], octets]

dele(which) -> 删除which,返回response

quit()


response:是一个字符串: +OK ...

['line', ...]:是一个列表,列表中‘’前面的是服务器返回的消息内容,后面的是邮件正文内容。


####################################################

#!/usr/bin/env python

from smtplib import SMTP
from poplib import POP3
from time import sleep

SMTPSVR = 'smtp.yourmail'
POP3SVR = 'pop3.yourmail'

#send to who
to_address = ['sendtowho']

#this will be  auto recognised
origHdrs = ['From: youremail',
            'To: sendtowho',
            'Subject: test']

#this is the real message you want to send
origBody = ['msgline1',
            'msgline2',
            'msgline3']

#the origHdrs and the origBody has a null line
origMsg = '\r\n\r\n'.join(['\r\n'.join(origHdrs),'\r\n'.join(origBody)])

#used for send mail with smtp
sendSvr = SMTP(SMTPSVR)
errs = sendSvr.sendmail('yourmail', to_address, origMsg)
sendSvr.quit()
assert len(errs) == 0, errs

#wait for the mail to come
sleep(10)

#used for recve mail with pop
recvSvr = POP3(POP3SVR)
recvSvr.user('yourname')
recvSvr.pass_('yourpassword')
rsp, msg, siz = recvSvr.retr(recvSvr.stat()[0])
sep = msg.index('')
recvBody = msg[sep+1:]
assert origBody == recvBody


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值