Send email gmail api
Here is an example of how to send an email using the Gmail API:
Step 1: Enable the Gmail API
- Go to the Google Cloud Console and create a new project.
- Click on "APIs & Services" and search for "Gmail API".
- Click on the "Gmail API" result and click on the "Enable" button.
- Create credentials for your project by clicking on "Create Credentials" and selecting "OAuth client ID".
- Choose "Other" as the application type and enter a name for your client ID.
- Click on "Create" and copy the client ID and client secret.
Step 2: Set up the Gmail API
- Install the Google API Client Library for your programming language of choice (e.g. Python, Java, etc.).
- Import the library and set up the API client:
import os import base64 from google.oauth2.credentials import Credentials from googleapiclient.discovery import build
Set up the API client
creds = Credentials.get_credentials() service = build('gmail', 'v1', credentials=creds)
**Step 3: Compose the email**
* Create a new email message using the `Messages` resource:
```python
message = {
'to': ['[email protected]'],
'from': '[email protected]',
'subject': 'Test email',
'body': {
'text': 'This is a test email.'
}
}
Step 4: Send the email
- Use the
Messages
resource to send the email:message = (base64.urlsafe_b64encode(json.dumps(message).encode())).decode() request = service.users().messages().send(userId='me', body={'raw': message}) response = request.execute()
Full code example
Here is the full code example in Python:
import os
import base64
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# Set up the API client
creds = Credentials.get_credentials()
service = build('gmail', 'v1', credentials=creds)
# Compose the email
message = {
'to': ['[email protected]'],
'from': '[email protected]',
'subject': 'Test email',
'body': {
'text': 'This is a test email.'
}
}
# Send the email
message = (base64.urlsafe_b64encode(json.dumps(message).encode())).decode()
request = service.users().messages().send(userId='me', body={'raw': message})
response = request.execute()
print(response)
Note
- Make sure to replace
[email protected]
and[email protected]
with the actual email addresses you want to use. - Make sure to enable the Gmail API and set up the API client correctly.
- This code example uses the
raw
message format, which allows you to send emails with attachments and other complex formatting. If you only need to send simple text emails, you can use thetext
message format instead.