Smtp Oauth With Python

 我的博客园:https://www.cnblogs.com/CQman/

GitHub

#基于Python语言的smtp Oauth 连接世纪互联运营的Office 365(或21V O365)的邮箱 

Authenticate an IMAP, POP or SMTP connection using OAuth

SASL XOAUTH2

OAuth 集成要求应用程序使用 SASL XOAUTH2 格式对访问令牌进行编码和传输。 SASL XOAUTH2 按以下格式将用户名和访问令牌编码在一起:

base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")

#Pyhton代码示例

# smtpOauth 
* 基于Python语言的smtp Oauth 连接China Office 365(或21V O365)的邮箱  
#Pyhton代码示例

import requests
import smtplib
import base64

# 定义发件人地址和密码以及收件人地址信息
username = 'S02@abc.com'
password = 'your username password'
recipient = 'recipient@abc.com'

# Get a token
url = 'https://login.partner.microsoftonline.cn/your tenant id/oauth2/v2.0/token'
data = {
    'grant_type': 'password',
    'client_id': 'your client id',
    'username': username,
    'password': password,
    'scope': 'https://partner.outlook.cn/.default',
    'client_secret': 'your client secret',
}
res = requests.post(url, data=data)
print("请求响应结果", res)
token = res.json().get('access_token')
print("访问令牌", token)

# 将username和token组合成SASL XOAUTH2 format
#对于Microsoft 365(或office 365)必须将^A替换为\x01
xoauth = "user=%s\x01auth=Bearer %s\x01\x01" % (username, token)
print("XOAUTH2格式", xoauth)

# base64编码
xoauth = xoauth.encode('ascii')
xoauth = base64.b64encode(xoauth)
print(xoauth)
xoauth = xoauth.decode('ascii')

#定义邮件主题内容等信息
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\nSo happy to hear from you!"
       % (username, recipient, "Smtp Oauth With Python",))

#连接SMTP服务器并发送邮件
try:
    smtp_conn = smtplib.SMTP('smtp.partner.outlook.cn', 587)
    # smtp_conn.set_debuglevel(True)
    smtp_conn.set_debuglevel(2)
    smtp_conn.ehlo()
    smtp_conn.starttls()
    smtp_conn.ehlo()
    smtp_conn.docmd('AUTH', 'XOAUTH2 ' + xoauth)
    smtp_conn.sendmail(username, recipient, msg)
    smtp_conn.quit()
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("邮件发送失败", e)

 

posted @ 2023-01-02 21:35  CQman  阅读(750)  评论(0编辑  收藏  举报