Python 接收邮件(有附件)

#!/usr/bin/env python
# coding=utf-8
# Python 2.7.3
# 获取邮件内容
import poplib
from email import parser

host = 'pop.163.com'
username = 'MyTest22@163.com'
password = 'xxxxxxxxx'

pop_conn = poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)

#Get messages from server:
# 获得邮件
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
#print messages

#print "--------------------------------------------------"
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#print messages

#Parse message intom an email object:
# 分析
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
i = 0
for message in messages:
	i = i + 1
	mailName = "mail%d.%s" % (i, message["Subject"])
	f = open(mailName + '.log', 'w');
	print >> f, "Date: ", message["Date"]
	print >> f, "From: ", message["From"]
	print >> f, "To: ", message["To"]
	print >> f, "Subject: ", message["Subject"]
	print >> f, "Data: "
	j = 0
	for part in message.walk():
		j = j + 1
		fileName = part.get_filename()
		contentType = part.get_content_type()
		# 保存附件
		if fileName:
			data = part.get_payload(decode=True)
			fileName = "%s.%d.%s" % (mailName, j, fileName)
			fEx = open(fileName, 'wb')
			fEx.write(data)
			fEx.close()
		elif contentType == 'text/plain' or contentType == 'text/html':
			#保存正文
			data = part.get_payload(decode=True)
			print >> f, data

	f.close()
pop_conn.quit()


参考: http://blog.csdn.net/xiarendeniao/article/details/8014886


### 回答1: 要在 Python接收邮件附件,你需要使用一个第三方库,例如:`imaplib` 或 `poplib`。这些库允许你连接到一个邮件服务器,下载邮件,并从邮件中提取附件。 以下是使用 `imaplib` 接收邮件附件的简单示例: ``` import imaplib import email mail = imaplib.IMAP4_SSL("imap.gmail.com") mail.login("your_email@gmail.com", "your_password") mail.select("inbox") result, data = mail.uid('search', None, "ALL") # 循环遍历所有邮件 for uid in data[0].split(): result, data = mail.uid('fetch', uid, '(RFC822)') raw_email = data[0][1].decode("utf-8") email_message = email.message_from_string(raw_email) # 循环遍历邮件中的附件 for part in email_message.walk(): if part.get_content_maintype() == "multipart": continue if part.get("Content-Disposition") is None: continue # 提取附件 file_name = part.get_filename() if bool(file_name): file_data = part.get_payload(decode=True) with open(file_name, "wb") as f: f.write(file_data) ``` 这是一个简单的示例,你可以根据你的需求进行更改。 ### 回答2: 要使用Python接收邮件附件,可以使用邮件协议库(如imaplib或poplib)来连接到邮件服务器,并使用email库来处理邮件附件。以下是一个简单示例: 1. 导入必要的库: ```python import imaplib import email ``` 2. 连接到邮件服务器: ```python mail = imaplib.IMAP4_SSL('mail.example.com') mail.login('your_email@example.com', 'your_password') ``` 3. 选择要访问的邮件文件夹(如收件箱): ```python mail.select('INBOX') ``` 4. 搜索带有附件邮件: ```python result, data = mail.search(None, 'ALL') ``` 5. 遍历搜索结果中的每封邮件: ```python for num in data[0].split(): result, data = mail.fetch(num, '(RFC822)') raw_email = data[0][1] email_message = email.message_from_bytes(raw_email) ``` 6. 确定邮件是否有附件: ```python if email_message.get_content_maintype() == 'multipart': for part in email_message.get_payload(): if part.get_filename(): filename = part.get_filename() attachment = part.get_payload(decode=True) # 处理附件 ``` 7. 关闭与邮件服务器的连接: ```python mail.logout() ``` 在处理附件时,你可以将其保存到本地文件或进行其他操作,例如解码、读取或传输。 请注意,此示例仅展示了基本的接收邮件附件的过程,实际操作可能还需要处理异常、过滤邮件等。具体情况还需要根据你所使用的邮件协议和服务器进行调整。 ### 回答3: Python可以使用标准库中的imaplib和email模块来接收邮件附件。 首先,需要使用imaplib库与邮件服务器建立连接并登录到邮箱。可以使用以下代码示例进行连接: ```python import imaplib server = imaplib.IMAP4_SSL("mail.example.com") server.login("your_email@example.com", "your_password") ``` 接下来,需要选择要操作的邮箱文件夹,使用select()方法选择收件箱(INBOX)或其他自定义文件夹: ```python server.select("INBOX") ``` 然后,使用imaplib库中的search()方法来搜索包含附件邮件。可以使用以下代码示例来搜索含有附件邮件: ```python status, messages = server.search(None, 'ALL') ``` 接着,使用email模块解析邮件内容和附件。可以使用以下代码示例来获取每封邮件附件信息: ```python import email for num in messages[0].split(): typ, data = server.fetch(num, "(RFC822)") msg = email.message_from_bytes(data[0][1]) if msg.get("Subject"): print("Subject:", msg.get("Subject")) 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: print("Attachment:", filename) ``` 最后,记得在程序结束后关闭与邮件服务器的连接: ```python server.close() server.logout() ``` 以上是使用imaplib和email模块来接收邮件附件的基本步骤。根据具体需求,还可以对发件人、时间等进行筛选和解析。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值