Table of contents

  1. Send mail from your Gmail account using Python
  2. Download attachments from Gmail using Gmail API in python
  3. Send mail with attachment from your Gmail account using Python

Send mail from your Gmail account using Python

Sending an email from a Gmail account using Python can be achieved with the smtplib and email libraries. Here's a step-by-step guide:

  1. Enable "Less secure app access" for your Gmail account:

    Before using this script, you need to allow less secure apps to access your Gmail account (not recommended for your primary email due to security concerns).

    Go to your Google Account settings -> Security -> Less secure app access -> Turn on.

  2. Install necessary libraries:

    If you haven't installed the email library yet, you can do so using pip:

    pip install secure-smtplib
    
  3. Python Script to Send Email:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    
    # Email setup
    sender_address = '[email protected]'
    sender_pass = 'your_password'
    receiver_address = '[email protected]'
    subject = 'Test Email using Python'
    body = 'This is a test email sent from Python.'
    
    # MIMEText object for email body
    message = MIMEMultipart()
    message['From'] = sender_address
    message['To'] = receiver_address
    message['Subject'] = subject
    message.attach(MIMEText(body, 'plain'))
    
    # Establish a connection to Gmail
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()  # Upgrade the connection to encrypted SSL/TLS
        server.login(sender_address, sender_pass)
        server.sendmail(sender_address, receiver_address, message.as_string())
        print('Email sent successfully!')
    except Exception as e:
        print(f"Error: {e}")
    finally:
        server.quit()
    

    Make sure to replace '[email protected]', 'your_password', and '[email protected]' with appropriate values.

  4. Security Concerns:

    • Storing your email and password directly in the script is a security risk. Consider using environment variables or encrypted configuration files to manage credentials.

    • It's generally not recommended to use your primary email with "Less secure app access" turned on. Consider creating a dedicated Gmail account just for sending these types of emails.

    • As of October 2020, Google has been deprecating "Less secure app access." It's possible they might disable this feature entirely in the future. If you need a long-term solution for sending emails programmatically, consider using dedicated email sending services like SendGrid, Mailgun, etc., which offer APIs for sending emails.


Download attachments from Gmail using Gmail API in python

To download attachments from Gmail using the Gmail API in Python, you'll need to use the Google API Client Library and authenticate your application to access the Gmail API. Here's a step-by-step guide:

  1. Set Up API Access:

    • Go to the Google Cloud Console.
    • Create a new project and enable the Gmail API for that project.
    • Generate OAuth 2.0 credentials (Client ID and Client Secret).
  2. Install Required Libraries:

    Install the necessary libraries using pip:

    pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
    
  3. Authenticate and Download Attachments:

    Create a Python script to authenticate with the Gmail API and download attachments:

    import base64
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from google.oauth2.credentials import Credentials
    
    # Set up API credentials
    credentials = Credentials.from_authorized_user_file('credentials.json')
    service = build('gmail', 'v1', credentials=credentials)
    
    def get_attachments(message_id):
        try:
            message = service.users().messages().get(userId='me', id=message_id).execute()
            for part in message['payload']['parts']:
                if part['filename']:
                    attachment = service.users().messages().attachments().get(userId='me', messageId=message_id, id=part['body']['attachmentId']).execute()
                    file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8'))
                    with open(part['filename'], 'wb') as f:
                        f.write(file_data)
        except HttpError as error:
            print(f"An error occurred: {error}")
    
    # Specify the message ID of the email containing attachments
    message_id = 'message_id_here'
    get_attachments(message_id)
    

    Replace 'credentials.json' with the path to your OAuth 2.0 credentials file. Also, replace 'message_id_here' with the actual message ID of the email containing the attachment.

  4. Run the Script:

    Run the script using Python:

    python download_attachments.py
    

This script uses the Gmail API to authenticate and fetch email messages, then it downloads attachments from the specified email. Make sure you've authorized your application and have the necessary permissions to access Gmail messages and attachments.


Send mail with attachment from your Gmail account using Python

To send an email with an attachment using Python, you can utilize the smtplib and email modules. Before we get to the code, there are some preliminary steps:

Preliminary Steps:

  1. Allow Less Secure Apps: For your Python script to access Gmail and send emails, you might need to allow less secure apps on your Google account. Visit this link and enable it. Note: This could expose your Gmail account to potential threats. So, after using this script, you might want to turn this setting off or use a throwaway Gmail account.

  2. Unlock Captcha: If you encounter authentication issues, you might need to allow access to your Google account: Allow access to your Google account.

Python Script to Send Email with Attachment:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

# Email and password
sender_email = "[email protected]"
sender_password = "your_password"
receiver_email = "[email protected]"

subject = "Subject of the Email"
body = "Hello, this is the body of the email."

msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject

msg.attach(MIMEText(body, 'plain'))

# Attach a file
filename = "file.txt"  # Name of the file
attachment = open(filename, 'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= " + filename)

msg.attach(part)

# Establish a connection and send email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()

Replace [email protected], your_password, and [email protected] with the appropriate email addresses and password. Also, adjust the filename variable to the correct path if your file is located somewhere else.

Security Note: Storing your password directly in the script is not recommended for security reasons. Consider using environment variables or other methods to keep your credentials secure. Another method is to use OAuth2 for authentication, which is more secure than using your email and password directly but requires more setup.


More Python Questions

More C# Questions