对我来说,@Prometheus 提供的答案是评论中提到的“RuntimeError: No auth token found . Authentication Flow required”。这可能是因为我的公司电子邮件启用了 2fa。所以我必须按照https://github.com/janscas/pyo365#authentication 和https://pypi.org/project/O365/#authentication 中提供的步骤进行操作
要使用 oauth,您首先需要在 Microsoft 应用程序注册门户注册您的应用程序。
- 登录Microsoft Application Registration Portal
- 创建一个应用,记下您的应用 ID (client_id)
- 在“应用程序机密”部分下生成新密码 (client_secret) 在“平台”部分下,添加新的 Web 平台并将 https://login.microsoftonline.com/common/oauth2/nativeclient" 设置为重定向 URL
- 转到 API 权限 > 添加权限 > Microsoft Graph > 委派权限,添加以下权限:
- 在 python 脚本下面运行获取访问令牌,该令牌将存储在当前目录中名为 o365_token.txt 的文件中
from O365 import Account
scopes = ["IMAP.AccessAsUser.All", "POP.AccessAsUser.All", "SMTP.Send", "Mail.Send", "offline_access"]
account = Account(credentials=('client_id_of_azureapp', 'client_secret_of_azureapp'))
result = account.authenticate(scopes=scopes) # request a token for this scopes
- 通过提供上一步生成的 authtoken 文件,使用以下脚本发送电子邮件。
from O365 import Account
from O365.utils.token import FileSystemTokenBackend
tk = FileSystemTokenBackend(token_path=".", token_filename="o365_token.txt")
credentials = ('client_id') # client secret not required
account = Account(credentials, auth_flow_type = 'public',token_backend=tk)
m = account.new_message()
m.to.add('user@company.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
注意:
如果您已获得管理员同意,或者您是管理员或 Azure 帐户,则可以跳过第 4、5、6 步并直接使用以下代码。
from O365 import Account
from O365.utils.token import FileSystemTokenBackend
tk = FileSystemTokenBackend(token_path=".", token_filename="o365_token.txt")
credentials = ('client_id', 'client_secret') # from step 2,3
account = Account(credentials, auth_flow_type = 'credentials', tenant_id="your_app_tenant_id") # tenant_id (required) available just below client_id in azure
if account.authenticate():
print('Authenticated!')
mailbox = account.mailbox("user@company.com") # Your email (required) from which you want to send email (your app should have permission to this email)
m = mailbox.new_message()
m.to.add('touser@company.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()