python 新浪的邮件的发送与接收

邮件的收发

以新浪邮箱为例,
使用SMTP发送一个邮件,使用POP3协议读取邮件列表,下载第一个邮件

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

print('***************SMPT发送邮件和POP3收邮件************')

SMTPSVR='smtp.sina.com' #smtp发送协议
POP3SVR='pop3.sina.com' #pop3接收协议
seder='xxxxx@sina.com' #发件箱
password='xxxxx' #发件箱密码
recips=['xxxxx@sina.com'] #收件人
origmsg='''\    #发送信息:发件人,收件人发送内容
From:%(who)s
To:%(who)s
Subject:first test

Hello World!
'''% {'who':seder}

#使用SMTP完成邮件的发送
sendSvr=SMTP(SMTPSVR) #创建一个smtp发送对象
sendSvr.login(seder,password) #登录操作
errs=sendSvr.sendmail(seder,recips,origmsg) #参数:发件人,收件人,邮件整体(消息头和消息体的字符串表示)
sendSvr.quit()
assert len(errs)==0,errs #,assert返回为假就会触发异常
print('smtp发送邮件完成')
sleep(5)

#使用pop3完成邮件的获取
recvSvr=POP3(POP3SVR) #创建一个pop3接收对象
recvSvr.user(seder) #设置用记名
recvSvr.pass_(password)
emailist=recvSvr.stat() #获取邮件列表
rsp,msg,siz=recvSvr.retr(emailist[0]) #下载第一个邮件
#print(msg) #查看返回所有信息
sep = msg.index(b'')  #查找列表中""空白元素,空白元素后面为邮件正文
recvBody = msg[sep+1:]  #根据空白元素定位获取邮件正文
print('pop3接收完成')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用 Python 进行邮件发送接收,可以使用 `smtplib` 和 `imaplib` 库。下面是一个简单的发送邮件的示例代码: ```python import smtplib from email.mime.text import MIMEText from email.header import Header # 发件人邮箱和密码 sender = 'your_email@example.com' password = 'your_password' # 收件人邮箱 receiver = 'recipient_email@example.com' # 邮件主题和内容 subject = 'Python 发送邮件测试' message = '这是一封 Python 发送邮件' # 创建邮件对象 msg = MIMEText(message, 'plain', 'utf-8') msg['From'] = Header(sender, 'utf-8') msg['To'] = Header(receiver, 'utf-8') msg['Subject'] = Header(subject, 'utf-8') # 发送邮件 try: smtpObj = smtplib.SMTP('smtp.example.com') smtpObj.login(sender, password) smtpObj.sendmail(sender, [receiver], msg.as_string()) print('邮件发送成功') except smtplib.SMTPException: print('邮件发送失败') ``` 要接收邮件,可以使用 `imaplib` 库。下面是一个简单的接收邮件的示例代码: ```python import imaplib import email # 邮箱账号和密码 username = 'your_email@example.com' password = 'your_password' # 邮箱服务器 imap_server = 'imap.example.com' # 连接到邮箱服务器 imapObj = imaplib.IMAP4_SSL(imap_server) imapObj.login(username, password) # 选择收件箱 imapObj.select() # 搜索邮件 typ, data = imapObj.search(None, 'ALL') # 获取最新一封邮件 email_id = data[0].split()[-1] typ, msg_data = imapObj.fetch(email_id, '(RFC822)') # 解析邮件 msg = email.message_from_bytes(msg_data[0][1]) subject = msg['Subject'] from_addr = msg['From'] to_addr = msg['To'] body = msg.get_payload() # 关闭连接 imapObj.close() imapObj.logout() ``` 注意,以上示例代码仅供参考,实际使用时需要根据具体情况进行修改。同时,发送邮件接收邮件的具体操作也会受到邮箱服务商的限制,需要根据具体邮箱服务商的文档进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值