为什么在使用Gmail API错误时我收到403授权被拒绝?

问题描述

我的问题是我无法将电子邮件发送到另一个邮件帐户。但是,我可以向自己的邮件帐户发送电子邮件。我生成的令牌使用发送许可。奇怪的是,我实际上成功地将邮件从我的帐户发送到了另一个帐户。但是我今天没有任何明显的理由而遭到拒绝。我没有超出任何限制,因为我总共只发送了大约3封邮件

注意:pipeline { agent any stages { stage('Hello') { steps { copyArtifacts projectName: 'pipeline1',fingerprintArtifacts: true,filter: 'hello.txt' } } } } 设置为FROM_EMAIL,TO_EMAIL设置为me

这是我的代码

a different mail account from the token owner

我收到的错误如下:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64

# Script is altered version of the one provided in the official documentation.

# If modifying these scopes,delete the file token.pickle.
ScopES = ['https://www.googleapis.com/auth/gmail.send']

# Directory path of this file
dir_path = os.path.dirname(os.path.realpath(__file__)) 

# Your credentials.json that you download from Google Cloud Platform
CREDENTIAL_FILE = dir_path + '/credentials.json'
TOKEN_FILE = dir_path + '/token.pickle'
USERNAME_FILE = dir_path + '/username.txt'

username = ''
with open(USERNAME_FILE,'r') as f:
    username = f.read().strip().split('\n')

FROM_EMAIL = username[0]
#FROM_EMAIL = 'me' # Just use: userId="me" when making your call to the Gmail API. For service account with domain-wide delegation the only time you specify the email address is for the 'sub' parameter when you're requesting the access token.
#print(FROM_EMAIL)

TO_EMAIL = username[1]
#print(TO_EMAIL)


def init():
    """ Authenticate with GMail API.
    """
    # The file token.pickle stores the user's access and refresh tokens,and is
    # created automatically when the authorization flow completes for the first
    # time.
    creds = None
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE,'rb') as token:
            creds = pickle.load(token)

    # If there are no (valid) credentials available,let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CREDENTIAL_FILE,ScopES)
            creds = flow.run_local_server(port=0)

        # Save the credentials for the next run
        with open('token.pickle','wb') as token:
            pickle.dump(creds,token)
            print('Authenticated')
            return
    else:
        print('Already authenticated')
    

def mail(subject,message_text):
    """Send mail using GMail API.
    """
    creds = None
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE,'rb') as token:
            creds = pickle.load(token)
    else:
        print('Not authenticated,run init()')

    service = build('gmail','v1',credentials=creds)
    message = create_message(FROM_EMAIL,TO_EMAIL,subject,message_text)

    print('Attempting to send message...')
    try:
        send_message(service,message)
    except Exception as e:
        print('Failed due to: ',e)
    print('Success!')


def create_message(sender,to,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
    # https://github.com/googleapis/google-api-python-client/issues/93
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    return {'raw': raw}


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 Exception as e:
        print('An error occurred: %s' % e)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)