python: smtp/pop/imap

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

邮件的服务器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


### QQ邮箱的POP3、SMTPIMAP协议设置 对于希望配置QQ邮箱以使用第三方邮件客户端(如Outlook、Thunderbird等),需要正确设置POP3、SMTP以及IMAP协议参数。 #### POP3服务器设置 - **服务器地址**: `pop.qq.com`[^1] - **端口**: SSL加密下为995,非SSL则为110[^2] #### IMAP服务器设置 - **服务器地址**: `imap.qq.com` - **端口**: 使用SSL时应设为993;未启用SSL的情况下则是143 #### SMTP服务器设置 - **服务器地址**: `smtp.qq.com` - **端口**: 当采用SSL连接时推荐使用465或者587端口。如果选择不使用SSL,则默认端口号为25 值得注意的是,在完成上述基本配置之后,还需要确保已经在QQ邮箱的安全中心开启了相应的服务,并取得了有效的授权码用于身份验证过程。这是因为出于安全考虑,默认情况下这些功能可能是被禁用的状态。一旦成功激活并获得授权码后,请妥善保管该代码以防丢失而需再次请求新的授权码。 ```python # Python示例:发送带有附件的电子邮件通过SMTP(SMTP部分) import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header def send_email_with_attachment(smtp_server, port, sender, password, receiver, subject, body, attachment_path=None): msg = MIMEMultipart() # 邮件正文 text_part = MIMEText(body,'plain','utf-8') msg.attach(text_part) if attachment_path is not None: with open(attachment_path,"rb") as file: part = MIMEApplication(file.read(),Name=basename(attachment_path)) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(attachment_path) msg.attach(part) server = smtplib.SMTP_SSL(smtp_server,port) server.login(sender,password) server.sendmail(sender,[receiver],msg.as_string()) server.quit() send_email_with_attachment('smtp.qq.com', 465, 'your_qq@qq.com', 'authorization_code_here', 'recipient@example.com', 'Test Email Subject', 'This is the content of test mail.') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值