用python实现邮箱发送文件和接收文件
时间: 2024-03-27 07:39:57 浏览: 17
你好,以下是用Python实现邮箱发送文件和接收文件的示例代码:
1. 发送文件
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
def send_email(subject, content, from_addr, password, to_addr, file_path):
# 邮件内容
message = MIMEMultipart()
message['From'] = Header(from_addr, 'utf-8')
message['To'] = Header(to_addr, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText(content, 'plain', 'utf-8'))
# 附件内容
with open(file_path, 'rb') as f:
mime = MIMEApplication(f.read())
mime.add_header('Content-Disposition', 'attachment', filename='file.txt')
message.attach(mime)
# 发送邮件
smtp = smtplib.SMTP('smtp.qq.com')
smtp.login(from_addr, password)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()
```
使用示例:
```python
send_email('测试邮件', '这是一封测试邮件,附件是文件', 'sender@qq.com', 'password', 'receiver@qq.com', 'file.txt')
```
2. 接收文件
接收邮件需要使用IMAP协议,以下是使用Python的imaplib库实现接收邮件的示例代码:
```python
import imaplib
import email
def receive_email(host, username, password):
# 连接邮箱
imap = imaplib.IMAP4_SSL(host)
imap.login(username, password)
imap.select()
# 搜索邮件
typ, data = imap.search(None, 'ALL')
mail_ids = data[0].split()
# 下载附件
for mail_id in mail_ids:
typ, data = imap.fetch(mail_id, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename:
with open(filename, 'wb') as f:
f.write(part.get_payload(decode=True))
# 关闭连接
imap.close()
imap.logout()
```
使用示例:
```python
receive_email('imap.qq.com', 'username@qq.com', 'password')
```
注意:在使用时需要先开启邮箱的IMAP服务,并且保证发送邮件和接收邮件的邮箱账号是同一个。