通过python脚本从Gmail邮箱下载附件

时间:2018-09-17 12:39:43

标签: python gmail

我正在尝试从我的Gmail帐户中获取附件。 我正在尝试一些代码示例,但所有示例都返回:“无法登录!” 由于某种原因,我无法登录IMAP服务器。

导入电子邮件     导入imaplib     导入操作系统

class FetchEmail():

    connection = None
    error = None

    def __init__(self, mail_server, username, password):
        self.connection = imaplib.IMAP4_SSL(imap.gmail.com)
        self.connection.login('test9484@gmail.com', '0562236632')
        self.connection.select(readonly=False) # so we can mark mails as read

    def close_connection(self):
        """
        Close the connection to the IMAP server
        """
        self.connection.close()

    def save_attachment(self, msg, download_folder="/tmp"):
        """
        Given a message, save its attachments to the specified
        download folder (default is /tmp)

        return: file path to attachment
        """
        att_path = "No attachment found."
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            att_path = os.path.join(download_folder, filename)

            if not os.path.isfile(att_path):
                fp = open(att_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

完成了什么

  • 启用了不太安全的访问权限
  • 已启用IMAP -您可能需要输入应用密码而不是常规密码。
  • 通过https://mail.google.com的Gmail网络版登录您的帐户。登录后,请尝试再次登录邮件应用。

0 个答案:

没有答案