第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用python從郵件中下載附件

使用python從郵件中下載附件

慕田峪7331174 2022-10-18 16:59:00
我有多封包含附件的電子郵件。我想下載帶有特定主題行的未讀電子郵件附件。例如,我收到一封主題為“EXAMPLE”并包含附件的電子郵件。那么它會(huì)如何下面的代碼,我試過(guò)但它不工作”這是一個(gè) Python 代碼#Subject line can be "EXAMPLE"       for subject_line in lst_subject_line:                 # typ, msgs = conn.search(None,'(UNSEEN SUBJECT "' + subject_line + '")')             typ, msgs = conn.search(None,'("UNSEEN")')             msgs = msgs[0].split()             print(msgs)             outputdir = "C:/Private/Python/Python/Source/Mail Reader"             for email_id in msgs:                    download_attachments_in_email(conn, email_id, outputdir)
查看完整描述

4 回答

?
HUH函數(shù)

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊

我能找到的大多數(shù)答案都已過(guò)時(shí)。

這是一個(gè)用于從 Gmail 帳戶下載附件的 python (>=3.6) 腳本。

確保檢查底部的過(guò)濾器選項(xiàng)并在您的谷歌帳戶上啟用不太安全的應(yīng)用程序。


import os

from imbox import Imbox # pip install imbox

import traceback


# enable less secure apps on your google account

# https://myaccount.google.com/lesssecureapps


host = "imap.gmail.com"

username = "username"

password = 'password'

download_folder = "/path/to/download/folder"


if not os.path.isdir(download_folder):

    os.makedirs(download_folder, exist_ok=True)

    

mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)

messages = mail.messages() # defaults to inbox


for (uid, message) in messages:

    mail.mark_seen(uid) # optional, mark message as read


    for idx, attachment in enumerate(message.attachments):

        try:

            att_fn = attachment.get('filename')

            download_path = f"{download_folder}/{att_fn}"

            print(download_path)

            with open(download_path, "wb") as fp:

                fp.write(attachment.get('content').read())

        except:

            print(traceback.print_exc())


mail.logout()



"""

Available Message filters: 


# Gets all messages from the inbox

messages = mail.messages()


# Unread messages

messages = mail.messages(unread=True)


# Flagged messages

messages = mail.messages(flagged=True)


# Un-flagged messages

messages = mail.messages(unflagged=True)


# Messages sent FROM

messages = mail.messages(sent_from='sender@example.org')


# Messages sent TO

messages = mail.messages(sent_to='receiver@example.org')


# Messages received before specific date

messages = mail.messages(date__lt=datetime.date(2018, 7, 31))


# Messages received after specific date

messages = mail.messages(date__gt=datetime.date(2018, 7, 30))


# Messages received on a specific date

messages = mail.messages(date__on=datetime.date(2018, 7, 30))


# Messages whose subjects contain a string

messages = mail.messages(subject='Christmas')


# Messages from a specific folder

messages = mail.messages(folder='Social')

"""

對(duì)于自簽名證書(shū),請(qǐng)使用:


...

import ssl

    

context = ssl._create_unverified_context()

mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=context, starttls=False)

...

筆記:


不太安全的應(yīng)用和您的 Google 帳戶


為幫助確保您的帳戶安全,自 2022 年 5 月 30 日起,Google 不再支持使用第三方應(yīng)用或設(shè)備,這些應(yīng)用或設(shè)備要求您僅使用您的用戶名和密碼登錄您的 Google 帳戶。


重要提示:此截止日期不適用于 Google Workspace 或 Google Cloud Identity 客戶。這些客戶的執(zhí)行日期將在稍后的 Workspace 博客上公布。


SRC


2022 年 8 月 22 日更新:您應(yīng)該能夠創(chuàng)建一個(gè)應(yīng)用程序密碼來(lái)解決“不太安全的應(yīng)用程序”功能消失的問(wèn)題。(后者仍然可以在我的企業(yè)帳戶中使用,但必須為我的消費(fèi)者帳戶創(chuàng)建一個(gè)應(yīng)用程序密碼。)使用 imaplib,我可以使用應(yīng)用程序密碼登錄。


查看完整回答
反對(duì) 回復(fù) 2022-10-18
?
小怪獸愛(ài)吃肉

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊

我發(fā)現(xiàn)這對(duì)我來(lái)說(shuō)最有效。只需在運(yùn)行程序時(shí)保持您的前景打開(kāi),它就會(huì)提取具有特定主題行的未讀郵件。


import datetime

import os

import win32com.client



path = os.path.expanduser("~/Documents/xyz/folder_to_be_saved")  #location o file today = datetime.date.today()  # current date if you want current


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  #opens outlook

inbox = outlook.GetDefaultFolder(6) 

messages = inbox.Items



def saveattachemnts(subject):

    for message in messages:

        if message.Subject == subject and message.Unread:

        #if message.Unread:  #I usually use this because the subject line contains time and it varies over time. So I just use unread


            # body_content = message.body

            attachments = message.Attachments

            attachment = attachments.Item(1)

            for attachment in message.Attachments:

                attachment.SaveAsFile(os.path.join(path, str(attachment)))

                if message.Subject == subject and message.Unread:

                    message.Unread = False

                break                

                

saveattachemnts('EXAMPLE 1')

saveattachemnts('EXAMPLE 2')


查看完整回答
反對(duì) 回復(fù) 2022-10-18
?
長(zhǎng)風(fēng)秋雁

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊

from imap_tools import MailBox


# get all attachments from INBOX and save them to files

with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:

    for msg in mailbox.fetch():

        for att in msg.attachments:

            print(att.filename, att.content_type)

            with open('C:/1/{}'.format(att.filename), 'wb') as f:

                f.write(att.payload)

https://github.com/ikvk/imap_tools


查看完整回答
反對(duì) 回復(fù) 2022-10-18
?
臨摹微笑

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊

我使用該解決方案從郵箱獲取附件。由您決定,下載或保存到本地變量。另外請(qǐng)注意,我首先閱讀了所有消息,因?yàn)榇蠖鄶?shù)時(shí)候盒子都是空的:


import imaplib

import email



class MailBox:

    SMTP_SERVER = 'imap.gmail.com'

    SMTP_PORT = 993

    USER = '<user_email>'

    PASSWORD = '<password>'


    def __init__(self):

        self.imap = imaplib.IMAP4_SSL(host=self.SMTP_SERVER, port=self.SMTP_PORT)

        self.imap.login(self.USER, self.PASSWORD)


    def __enter__(self):

        self.emails = self._get_all_messages()


    def __exit__(self, exc_type, exc_value, exc_traceback):

        self.imap.close()

        self.imap.logout()


    def fetch_message(self, num=-1):

        _, data = self.imap.fetch(self.emails[num], '(RFC822)')

        _, bytes_data = data[0]

        email_message = email.message_from_bytes(bytes_data)

        return email_message


    def get_attachment(self, num=-1):

        for part in self.fetch_message(num).walk():

            if part.get_content_maintype() == 'multipart' or part.get('Content-Disposition') is None:

                continue

            if part.get_filename():

                return part.get_payload(decode=True).decode('utf-8').strip()


    def _get_all_messages(self):

        self.imap.select('Inbox')

        status, data = self.imap.search(None, 'ALL')

        return data[0].split()


查看完整回答
反對(duì) 回復(fù) 2022-10-18
  • 4 回答
  • 0 關(guān)注
  • 507 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)