尝试使用Google API发送电子邮件时出现错误。
在线:
message = (service.users().messages().send(userId=user_id, body=message)\
.execute())
错误消息:
google.auth.exceptions.RefreshError :(“'unauthorized_client:未经授权的客户端可以使用此方法检索访问令牌。','{\ n“ error”:“ unauthorized_client”,\ n“ error_description”:“客户端未经授权使用此方法检索访问令牌。“ \ n}')
我使用https://developers.google.com/gmail/api/guides/sending中的一个例子 进行少量修改:
from __future__ import print_function
from googleapiclient.discovery import build
from apiclient import errors
from httplib2 import Http
from email.mime.text import MIMEText
import base64
from google.oauth2 import service_account
import os
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string().encode())\
.decode()}
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)\
.execute())
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
def service_account_login():
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = '{}\\service-key.json'.format(__path__)
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(EMAIL_FROM)
service = build('gmail', 'v1', credentials=delegated_credentials)
return service
EMAIL_FROM = 'email_from@gmail.com'
EMAIL_TO = 'email_to@ikea.com'
EMAIL_SUBJECT = 'Hello from Arnold!'
EMAIL_CONTENT = 'Hello, this is a Arnold'
__path__ = os.path.dirname(os.path.realpath(__file__))
service = service_account_login()
message = create_message(EMAIL_FROM, EMAIL_TO, EMAIL_SUBJECT, EMAIL_CONTENT)
sent = send_message(service,'me', message)
如何避免出现此错误消息并发送电子邮件。