python 利用imap接收邮件,并保存附件

def SaveAttachImap():# login the imap server ,retrive the  new mails ,and download the attachments.

    M = imaplib.IMAP4(mail_host,mail_port)
    #print M


    M.login(mail_user,mail_pass)

    M.select('INBOX',False)
    #result, message = M.select('INBOX',False)
    typ, data = M.search(None, 'UNSEEN')
    print data
    for num in string.split(data[0]):
        try:
            typ, data = M.fetch(num, '(RFC822)')
            #print data
            msg = email.message_from_string(data[0][1])
            for par in msg.walk():
            #if not par.is_multipart():
                name = par.get_filename()
                print 'name',name

                #name2 = par.get_filename()
                #print 'name2',name2


                if name:
                    dstdir =dirname+name
                    print 'dirname',dstdir
                    #print 'name',name
                    data = par.get_payload(decode=True)
                    #print dstdir
                    try:
                        f = open(dstdir, 'wb') #注意一定要用wb来打开文件,因为附件一般都是二进制文件
                        print 'save attfile %s succeed'%dstdir
                    except:
                        print 'open  file name error'
                    f.write(data)
                    f.close()

                #print "_______________________________"
        except Exception,e:
            print 'got msg error: %s' % e

    M.close()
    M.logout()

### 回答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、付费专栏及课程。

余额充值