لقد قمت بتضمين الرسالة الخطأ التي تتلقاها “An error occurred: b’Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSIKTUlNRS…”. هذا الخطأ يعني أن هناك مشكلة في تسلسل البيانات إلى JSON. يبدو أن المشكلة تكمن في طريقة التسلسل التي تستخدمها للرسالة في الجزء الأخير من الكود.
بدلاً من استخدام base64.b64encode(message.as_bytes())
لتسلسل الرسالة إلى صيغة قابلة للإرسال عبر البريد الإلكتروني، يمكنك استخدام الدالة as_string()
بدلاً من as_bytes()
للحصول على سلسلة نصية تمثل الرسالة بشكل صحيح. قم بتغيير السطر:
pythonbody = {'raw': base64.b64encode(message.as_bytes())}
إلى:
pythonbody = {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
سيقوم هذا التغيير بتسلسل الرسالة بشكل صحيح ومن ثم إرسالها عبر خدمة Gmail API بدون مشاكل.
المزيد من المعلومات
إذا كنت تواجه مشكلة “not JSON serializable”، فهذا يعني أن الكائن الذي تحاول تسلسله إلى JSON لا يمكن تسلسله بشكل افتراضي. في حالة الكود الذي قدمته، يبدو أن المشكلة تكمن في محاولتك تسلسل كائن bytes
المستخدم لتمثيل محتوى الرسالة بواسطة base64.b64encode()
.
لحل هذه المشكلة، يمكنك استخدام الدالة base64.urlsafe_b64encode()
لتسلسل البيانات بشكل صحيح. هناك طرق أخرى لحل هذه المشكلة، مثل استخدام دالة json.dumps()
لتسلسل الكائنات القابلة للتسلسل إلى JSON بدلاً من تسلسل البيانات بنفسك.
إليك كيف يمكن تعديل الكود لحل هذه المشكلة:
pythonimport base64
import httplib2
from email.mime.text import MIMEText
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow
# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'client_secret.json'
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
# Location of the credentials storage file
STORAGE = Storage('gmail.storage')
# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()
# Try to retrieve credentials from storage or run the flow to generate them
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, STORAGE, http=http)
# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)
# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)
# create a message to send
message = MIMEText("Message")
message['to'] = "[email protected]"
message['from'] = "[email protected]"
message['subject'] = "Subject"
body = {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
# send it
try:
message = (gmail_service.users().messages().send(userId="me", body=body).execute())
print('Message Id: %s' % message['id'])
print(message)
except Exception as error:
print('An error occurred: %s' % error)
بعد هذا التعديل، يجب أن يتم إرسال الرسالة بدون مشاكل وتجنب الخطأ “not JSON serializable”.