UCONN

UCONN
UCONN

Thursday, July 22, 2021

Python Gmail API from Georgiy Zemlevskiy, 7/22/2021, 10:29 PM, English, 7/22/2021, 10:29 PM

Your assigned language is: English
Classroom blog: googleclouduconn.blogspot.com

7/22/2021, 10:29 PM

Requirement number 2
New page needed to send text
send communications.
use text box and send button
When send is pushed

Message
Hello World
---> SEND←--
How do we loop thru all records in table?
Loop thru all records in the client table
E.G
Email: john.iacovacci1@gmail.com
Language: es
Translate Message
tmsg = customer['message'']
tlang = language field from datastore table
result = translate_client.translate(tmsg, target_language=tlang)
Need to use GMAIL API

https://developers.google.com/gmail/api/quickstart/python
Remember share project with team.
Put credentials in same path of python code
Copy up file from local download and rename to credentials.json
Credentials
Do your best to try to get this process running.
Following code is from Georgiy Zemlevskiy
Hello, following are the instructions to create a python program that
sends an email using the Gmail API.
Instructions:
1. Enable Gmail API.
2. Setup credentials. (guide here, but I didn't use it)
a. Click "Create Credentials", it should prompt you to create an
OAuth consent screen if you haven't already created credentials
before.
b. Follow the steps and configure it how you like.
c. Configure the scopes. For my example, you only need the "send
email" scope, which can be added by clicking the "Add or Remove
Scopes" button and adding "https://googleapis.com/auth/gmail.send".
d. Add test users. Add the emails of the people in your group
(including yourself), and whoever you want to test the app for you.
e. Verify that the information you entered is what correct.
f. Next, click the "Create Credentials" button again. Click OAuth
client ID, click "desktop application". Set a name, and click create!
To use this, download the secrets file by clicking the download icon.
You should put this in the directory with your app code, and rename it
to "credentials.json".
You are done with credentials setup!
3. Implement functionality.
a. Head over to the Gmail API quickstart. (I used python, but I
assume things will be similar with Java to a point.)
b. Follow the steps (install the client library, copy the code, etc.)
c. Run the file. ("python yourFileName.py" in the terminal)
d. If everything has been done correctly, a browser window/tab
should open with the OAuth consent screen. Follow the authentication
flow. Once completed, the terminal should show the labels of the
account you signed in with to the OAuth consent screen.
e. Next, duplicate the quickstart file, and remove the section
under "#Call the Gmail API".
f. Head over to the Gmail API documentation, specifically the
sending email page. Copy the create_message and send_message functions
to your new file.
g. There will be some errors. To remove them, add the following to
the imports at the top of your file:
from apiclient import errors
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64
At the end of the create_message function, replace the return
statement with this, which returns a message object (which is what we
need) rather than an encoded string:
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
Also, at the end of the send_message function, wrap the content of the
print statements in parentheses like so:

print ('Message Id: %s' % message['id'])
...
print ('An error occurred: %s' % error)
h. Finally, add a statement that creates and sends the email, like
so (add the email you want to send to instead of
<recipientEmailHere>):
send_message(service, 'me', create_message('me',
'<recipientEmailHere>', 'test', 'test'))
If you did everything correctly, an email with the subject and content
of "test" should be sent to your recipient. If something is not
working, and you are stumped, feel free to use the code that I have
attached.
Note: while this process doesn't require more dependencies than I had
specified, if you want to continue to develop Google Cloud apps
locally, you need to download and install the Google Cloud SDK and
appropriate libraries/extensions for translation, datastore, app
engine (on the page with the Google Cloud SDK) etc.
Hope everything worked!
Georgiy Zemlevskiy.
Attachments area

ReplyForward


from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
#Extra imports to fix errors(missing dependencies/imports)
from apiclient import errors
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64

#send scope - allows the program to send email on users' behalf
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
#security/authorization stuff, dont modify unless you really know what
you're doing
def main():
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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(
#desktopcredentials.json contains the secrets file for
the desktop OAuth client ID
#web credentials.json contains the secrets file for the
webapp OAuth client ID (DOESN'T WORK)
'desktopcredentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())

service = build('gmail', 'v1', credentials=creds)

#send email (had personal info so commented out. for test purposes
only. message and subject
# hardcoded, programmatically selected as they should(will be))
#send_message(service, 'me', create_message('me',
'<recipientEmailHere>', 'test', 'test'))

#function to create a message, copied from Gmail API docs, slightly
modified to fix errors
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()}

#function to send a created message, copied from Gmail API docs,
slightly modified to fix errors
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)



if __name__ == '__main__':
main()

No comments:

Post a Comment

Disable Billing

Search for Billing Manage billing accounts Go to MYPROJECTS CLICK ON THE 3 BUTTON Actions Then hit disable