How to send HTML Formatted emails, through the gmail-api for python

How to send HTML Formatted emails, through the gmail-api for python

To send HTML-formatted emails through the Gmail API in Python, you can use the google-auth and google-auth-oauthlib libraries for authentication, and the googleapiclient.discovery module to interact with the Gmail API. Here's a step-by-step guide:

  1. Set Up the Gmail API: Before you begin, you need to create a project in the Google Cloud Console, enable the Gmail API, and create credentials. Follow the steps outlined in Google's documentation: https://developers.google.com/gmail/api/quickstart

  2. Install Required Packages: Install the necessary packages using pip:

    pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client 
  3. Python Code: Here's an example of sending an HTML-formatted email using the Gmail API:

from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google.auth.transport.requests import Request from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import base64 import os.path # Set up Gmail API SCOPES = ['https://www.googleapis.com/auth/gmail.send'] creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) 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('credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('gmail', 'v1', credentials=creds) # Create MIME message message = MIMEMultipart() message['to'] = 'recipient@example.com' message['subject'] = 'HTML Email Example' html_content = """ <html> <body> <h1>Hello, this is an HTML email!</h1> <p>This is the content of the email.</p> </body> </html> """ message.attach(MIMEText(html_content, 'html')) # Send the email raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8') try: message = service.users().messages().send(userId='me', body={'raw': raw_message}).execute() print('Email sent:', message['id']) except HttpError as error: print('An error occurred:', error) 

Replace 'recipient@example.com' with the recipient's email address, and make sure you have the credentials.json file from the Gmail API setup in your working directory.

This example uses OAuth2 for authentication, creates an HTML-formatted email using MIMEMultipart and MIMEText, encodes the email message, and sends it using the Gmail API.

Remember to handle exceptions and error cases according to your use case.

Examples

  1. "Gmail API Python send HTML email example"

    • Description: This query seeks a basic example demonstrating how to send HTML-formatted emails using the Gmail API in Python.
    • Code:
      from googleapiclient.discovery import build from google.oauth2.credentials import Credentials def send_html_email(service, sender, to, subject, html_message): message = create_message(sender, to, subject, html_message) send_message(service, "me", message) def create_message(sender, to, subject, html_message): message = { "to": to, "from": sender, "subject": subject, "html": html_message } return message def send_message(service, user_id, message): try: message = (service.users().messages().send(userId=user_id, body=message) .execute()) print("Message sent successfully!") return message except Exception as e: print(f"An error occurred: {e}") 
  2. "Gmail API Python send HTML email with attachments"

    • Description: This query focuses on sending HTML emails with attachments using the Gmail API in Python.
    • Code:
      from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import base64 def create_message_with_attachment(sender, to, subject, message_text, file_path): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text, 'html') message.attach(msg) with open(file_path, 'rb') as file: attachment = MIMEImage(file.read(), _subtype="pdf") attachment.add_header('Content-Disposition', 'attachment', filename=file_path) message.attach(attachment) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} def send_message(service, user_id, message): try: message = (service.users().messages().send(userId=user_id, body=message) .execute()) print("Message sent successfully!") return message except Exception as e: print(f"An error occurred: {e}") 
  3. "Gmail API Python send HTML email with inline images"

    • Description: This query targets sending HTML emails with inline images using the Gmail API in Python.
    • Code:
      from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import base64 def create_message_with_inline_image(sender, to, subject, html_message, image_path): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(html_message, 'html') message.attach(msg) with open(image_path, 'rb') as file: img = MIMEImage(file.read()) img.add_header('Content-ID', '<image>') message.attach(img) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} def send_message(service, user_id, message): try: message = (service.users().messages().send(userId=user_id, body=message) .execute()) print("Message sent successfully!") return message except Exception as e: print(f"An error occurred: {e}") 

More Tags

ini flutter-futurebuilder figure amazon-cloudwatchlogs r-caret presentviewcontroller text-segmentation sql-job jquery uipageviewcontroller

More Python Questions

More Date and Time Calculators

More Gardening and crops Calculators

More Other animals Calculators

More Electronics Circuits Calculators