This is code to get creds:
SERVICE_ACCOUNT_FILE = 'myJsonFile.json'
scopes = ['https://www.googleapis.com/auth/gmail.send']
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,)
creds_with_scope = credentials.with_scopes(scopes=scopes)
if creds_with_scope.token == None or creds_with_scope.valid == False:
creds_with_scope.refresh(Request())
Using this code I get a valid Token. But when I try to login to SMTP server with this creds in the code:
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender_email, creds)
server.sendmail(sender_email, receiver_email, email_text)
server.quit()
I get an error:
(535, b'5.7.8 Username and Password not accepted. For more information, go to\n5.7.8 https://support.google.com/mail/?p=BadCredentials f26-20020a7bc8da000000b0041076151a8csm579297wml.14 - gsmtp')
I than tried to apply only Token attribute such as:
server.login('[email protected]', creds.token)
But I get: Connection unexpectedly closed and no e-mail was sent at all.
I am wondering how I could I make a login to SMTP server with OAuth2 connection and send an e-mail?