yagmail

0.15.293 · active · verified Mon Apr 13

yagmail (Yet Another GMAIL client) is a Python library designed to simplify sending emails, particularly with Gmail accounts, by abstracting away the complexities of SMTP, MIME, and headers. It is currently at version 0.15.293 and is actively maintained, with regular updates addressing features and compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates sending a basic email using yagmail with an App Password (recommended over your main Gmail password). For enhanced security, especially in production, consider setting up OAuth2 authentication as detailed in yagmail's documentation. Ensure your sender email and password (or app password) are configured, ideally via environment variables.

import yagmail
import os

# It's recommended to use App Passwords for Gmail or OAuth2.
# Store your email and app password in environment variables for security.
# For OAuth2, configure it via yagmail.SMTP('your_email@gmail.com', oauth2_file='path/to/oauth2_creds.json')
# See yagmail docs for detailed OAuth2 setup.

SENDER_EMAIL = os.environ.get('YAGMAIL_SENDER_EMAIL', 'your_email@gmail.com')
SENDER_APP_PASSWORD = os.environ.get('YAGMAIL_SENDER_APP_PASSWORD', 'your_app_password')
RECIPIENT_EMAIL = os.environ.get('YAGMAIL_RECIPIENT_EMAIL', 'recipient@example.com')

try:
    # Initialize yagmail with your Gmail account and app password
    yag = yagmail.SMTP(user=SENDER_EMAIL, password=SENDER_APP_PASSWORD)

    # Send an email
    subject = 'Hello from yagmail!'
    contents = [
        'This is the body of the email.',
        'You can also send HTML content.',
        '<p>This is <b>bold</b> HTML content!</p>'
    ]

    yag.send(
        to=RECIPIENT_EMAIL,
        subject=subject,
        contents=contents
    )
    print(f'Email sent successfully from {SENDER_EMAIL} to {RECIPIENT_EMAIL}')
except Exception as e:
    print(f'Failed to send email: {e}')

view raw JSON →