socket邮件客户端 python
时间: 2024-12-26 17:11:43 浏览: 0
在Python中,可以使用socket库创建简单的邮件客户端,通常结合IMAP4(Internet Message Access Protocol version 4)协议来读取邮件,SMTP(Simple Mail Transfer Protocol)协议来发送邮件。以下是一个简化的示例:
```python
import imaplib
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 1. 连接IMAP服务器
def imap_login(host, user, password):
mail = imaplib.IMAP4_SSL(host)
mail.login(user, password)
return mail
# 2. 检索并下载邮件
def fetch_emails(mail, mailbox='INBOX', criteria='ALL'):
mail.select(mailbox)
result, data = mail.uid('search', None, criteria)
uids = data[0].split()
for uid in uids:
_, msg_data = mail.uid('fetch', uid, '(RFC822)')
yield msg_data[0][1]
# 3. 发送邮件
def send_email(smtp_server, sender, receiver, subject, body, password):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(sender, password)
text = msg.as_string()
server.sendmail(sender, receiver, text)
server.quit()
# 使用示例
host = "imap.example.com"
username = "your_username"
password = "your_password"
imap_mail = imap_login(host, username, password)
email_list = list(fetch_emails(imap_mail))
for msg in email_list:
# 邮件内容处理...
send_email("smtp.example.com", "sender@example.com", "receiver@example.com",
"邮件主题", "邮件正文", password)
# 关闭连接
imap_mail.close()
imap_mail.logout()
```
阅读全文