【问题标题】:How to setup connection to local hmail server in python?如何在 python 中设置与本地 hmail 服务器的连接?
【发布时间】:2021-09-20 13:46:22
【问题描述】:

我已经在我的本地机器上设置了一个 hmailserver。我还使用了一个读取电子邮件的 python 脚本。当我连接到 Outlook 时,python 脚本运行良好。但是我的 hmailserver 的本地连接有问题。我希望脚本连接到我的本地电子邮件服务器(hmailserver)并从那里阅读电子邮件。我很难建立这个连接,而且我找不到与 hmailserver 和 python 相关的好的文档。

import email
import imaplib

EMAIL = 'user1@test.com'
PASSWORD = 'test123'
SERVER = '0.0.0.0/143'#'smtp-mail.outlook.com'

# connect to the server and go to its inbox
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
# we choose the inbox but you can select others
mail.select('inbox')

# we'll search using the ALL criteria to retrieve
# every message inside the inbox
# it will return with its status and a list of ids
status, data = mail.search(None, 'ALL')
# the list returned is a list of bytes separated
# by white spaces on this format: [b'1 2 3', b'4 5 6']
# so, to separate it first we create an empty list
mail_ids = []
# then we go through the list splitting its blocks
# of bytes and appending to the mail_ids list
for block in data:
    # the split function called without parameter
    # transforms the text or bytes into a list using
    # as separator the white spaces:
    # b'1 2 3'.split() => [b'1', b'2', b'3']
    mail_ids += block.split()

# now for every id we'll fetch the email
# to extract its content
for i in mail_ids:
    # the fetch function fetch the email given its id
    # and format that you want the message to be
    status, data = mail.fetch(i, '(RFC822)')

    # the content data at the '(RFC822)' format comes on
    # a list with a tuple with header, content, and the closing
    # byte b')'
    for response_part in data:
        # so if its a tuple...
        if isinstance(response_part, tuple):
            # we go for the content at its second element
            # skipping the header at the first and the closing
            # at the third
            message = email.message_from_bytes(response_part[1])

            # with the content we can extract the info about
            # who sent the message and its subject
            mail_from = message['from']
            mail_subject = message['subject']

            # then for the text we have a little more work to do
            # because it can be in plain text or multipart
            # if its not plain text we need to separate the message
            # from its annexes to get the text
            if message.is_multipart():
                mail_content = ''

                # on multipart we have the text message and
                # another things like annex, and html version
                # of the message, in that case we loop through
                # the email payload
                for part in message.get_payload():
                    # if the content type is text/plain
                    # we extract it
                    if part.get_content_type() == 'text/plain':
                        mail_content += part.get_payload()
            else:
                # if the message isn't multipart, just extract it
                mail_content = message.get_payload()

            # and then let's show its result
            print(f'From: {mail_from}')
            print(f'Subject: {mail_subject}')
            print(f'Content: {mail_content}')

上面是我正在使用的代码,连接到我的 Outlook 电子邮件工作正常 (smtp-mail.outlook.com)。但是当我将服务器替换为连接到端口 143 上的 0.0.0.0 的本地主机时,我收到以下错误

File "c:/Users/yehya/Desktop/relay.py", line 10, in <module>
    mail = imaplib.IMAP4_SSL(SERVER)
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 1297, in __init__
    IMAP4.__init__(self, host, port)
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 198, in __init__
    self.open(host, port)
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 1310, in open
    IMAP4.open(self, host, port)
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 303, in open
    self.sock = self._create_socket()
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 1300, in _create_socket
    sock = IMAP4._create_socket(self)
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\imaplib.py", line 293, in _create_socket
    return socket.create_connection((host, self.port))
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\socket.py", line 787, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\yehya\AppData\Local\Programs\Python\Python38\lib\socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

感谢任何帮助

【问题讨论】:

  • 本地主机为 127.0.0.1。端口不包含在服务器字符串中,它是一个单独的参数。并且端口 143 不是 SSL,所以总而言之,您需要 imaplib.IMAP('127.0.0.1', 143) 之类的东西(尽管 143 是隐含的,不需要指定)

标签: python email localhost imaplib hmail-server


【解决方案1】:

问题在于 IP 地址0.0.0.0。这是一个“监听”地址,而不是localhost 地址。请参阅the wikipedia entry

如果你想循环回同一台机器,你需要使用IP地址127.0.0.1。对应wikipedia article

我也认为服务器地址中的/ 可能不正确。我认为您需要将其替换为 : 以指定端口。

换行:

SERVER = '0.0.0.0/143'#'smtp-mail.outlook.com'

到下面的一个:

SERVER = '127.0.0.1:143'#'smtp-mail.outlook.com'

【讨论】:

  • imaplib 根本不将端口作为服务器字符串的一部分,它必须是一个单独的参数。 conn = imaplib.IMAP(‘127.0.0.1’, 143).
【解决方案2】:

max 的评论是正确的。正确的格式是 mail = imaplib.IMAP4_SSL(SERVER,143)。在我的情况下,服务器也不需要 ssl 方法。所以mail=imaplib.IMAP4(SERVER,143)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-14
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    相关资源
    最近更新 更多