使用 Python 连接 Exchange 邮箱

发布于 2024-07-09 01:51:14 字数 1454 浏览 6 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一百个冬季 2024-07-16 01:51:14

我知道这是一个旧线程,但是...

如果您使用的是 Exchange 2007 或更高版本,或者 Office365,请查看 Exchange Web 服务。 它是一个非常全面的基于 SOAP 的 Exchange 界面,您几乎可以执行 Outlook 能够执行的任何操作,包括委托或模拟对其他用户帐户的访问。

https:// learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-reference-for-exchange

更新:我已经发布了 PyPI 上的 Python EWS 客户端,支持自动发现、日历、收件箱、任务、联系人等:

from exchangelib import DELEGATE, Account, Credentials

credentials = Credentials(
    username='MYDOMAIN\\myusername',  # Or [email protected] for O365
    password='topsecret'
)
a = Account(
    primary_smtp_address='[email protected]', 
    credentials=credentials, 
    autodiscover=True, 
    access_type=DELEGATE
)
# Print first 100 inbox messages in reverse order
for item in a.inbox.all().only('subject').order_by('-datetime_received')[:100]:
    print(item.subject)

I know this is an old thread, but...

If you're using Exchange 2007 or newer, or Office365, take a look at Exchange Web Services. It's a pretty comprehensive SOAP-based interface for Exchange, and you can do pretty much anything Outlook is able to do, including delegate or impersonation access to other user accounts.

https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-reference-for-exchange

UPDATE: I have released a Python EWS client on PyPI that supports autodiscover, calendars, inbox, tasks, contacts, and more:

from exchangelib import DELEGATE, Account, Credentials

credentials = Credentials(
    username='MYDOMAIN\\myusername',  # Or [email protected] for O365
    password='topsecret'
)
a = Account(
    primary_smtp_address='[email protected]', 
    credentials=credentials, 
    autodiscover=True, 
    access_type=DELEGATE
)
# Print first 100 inbox messages in reverse order
for item in a.inbox.all().only('subject').order_by('-datetime_received')[:100]:
    print(item.subject)
心在旅行 2024-07-16 01:51:14

我明白了,要连接到出站交换,您需要像这样连接:

import smtplib

url = YOUR_EXCHANGE_SERVER
conn = smtplib.SMTP(url,587)
conn.starttls()
user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)
conn.login(user,password)

现在您可以像正常连接一样发送

message = 'From: FROMADDR\nTo: TOADDRLIST\nSubject: Your subject\n\n{}'
from, to = fromaddr,toaddrs
txt = 'This is my message'
conn.sendmail(fromaddr,toaddrs,msg.format(txt))

以从收件箱获取邮件,它有点不同,

import imaplib

url = YOUR_EXCHANGE_URL
conn = imaplib.IMAP4_SSL(url,993)
user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)
conn.login(user,password)
conn.select('INBOX')
results,data = conn.search(None,'ALL')
msg_ids = data[0]
msg_id_list = msg_ids.split()

这会给您一个消息 ID 列表
现在您可以使用它来获取电子邮件

latest_email_id = msg_id_list[-1]
result,data = conn.fetch(latest_email_id,"(RFC822)")
raw_email = data[0][1]

raw_email 是您的电子邮件消息,但它不是很漂亮,如果您想解析它,请执行类似的操作,

from email.parser import Parser

p = Parser()
msg = p.parsestr(raw_email)

现在您可以执行

msg.get('From')
msg.get('Subject')

或获取内容

msg.get_payload()

,但如果它是一条多部分消息,您将需要要进行更多处理,幸运的是,递归解决方案非常适合这种情况,

def process_multipart_message(message):
    rtn = ''
    if message.is_multipart():
        for m in message.get_payload():
            rtn += process_multipart_message(m)
    else:
        rtn += message.get_payload()
    return rtn

现在

msg_contant = process_multipart_message(msg)

每次都会给您完整的消息。

Ive got it, to connect to outbound exchange you need to connect like this:

import smtplib

url = YOUR_EXCHANGE_SERVER
conn = smtplib.SMTP(url,587)
conn.starttls()
user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)
conn.login(user,password)

now you can send like a normal connection

message = 'From: FROMADDR\nTo: TOADDRLIST\nSubject: Your subject\n\n{}'
from, to = fromaddr,toaddrs
txt = 'This is my message'
conn.sendmail(fromaddr,toaddrs,msg.format(txt))

to get the mail from your inbox its a little different

import imaplib

url = YOUR_EXCHANGE_URL
conn = imaplib.IMAP4_SSL(url,993)
user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)
conn.login(user,password)
conn.select('INBOX')
results,data = conn.search(None,'ALL')
msg_ids = data[0]
msg_id_list = msg_ids.split()

this gives you a list of message id'
s that you can use to get your emails

latest_email_id = msg_id_list[-1]
result,data = conn.fetch(latest_email_id,"(RFC822)")
raw_email = data[0][1]

now raw_email is your email messsage, but its not very pretty, if you want to parse it do somthing like this

from email.parser import Parser

p = Parser()
msg = p.parsestr(raw_email)

now you can do

msg.get('From')
msg.get('Subject')

or for the content

msg.get_payload()

but if its a multipart message your going to need to do a little more processing, luckly a recursive solution is perfect for this situation

def process_multipart_message(message):
    rtn = ''
    if message.is_multipart():
        for m in message.get_payload():
            rtn += process_multipart_message(m)
    else:
        rtn += message.get_payload()
    return rtn

now

msg_contant = process_multipart_message(msg)

will give you the whole message every time.

陌伤浅笑 2024-07-16 01:51:14

我非常确定,如果不使用 Outlook 和 MAPI 配置文件,这是不可能的。 如果您能甜言蜜语地说服您的邮件管理员在 Exchange 服务器上启用 IMAP,那么您的生活会轻松很多。

I'm pretty sure this is going to be impossible without using Outlook and a MAPI profile. If you can sweet talk your mail admin into enabling IMAP on the Exchange server it would make your life a lot easier.

时光沙漏 2024-07-16 01:51:14

您必须找到一种方法以该特定用户的身份运行该进程。

看到这个。

我认为 pywin32 .CreateProcessAsUser 是您需要走的路径的起点。 最后一次编辑。 登录的用户句柄是通过使用 win32security.LogonUser 方法获取的

You'll have to find a way to run the process as that particular user.

See this.

I think pywin32.CreateProcessAsUser is the start of the path you need to go down. One last edit. The logged on user handle is obtained from using the win32security.LogonUser method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文