yagmail
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
- breaking Google has deprecated 'Less secure app access'. Older tutorials suggesting this method will no longer work. Attempting to use your main Gmail password without 2FA and an App Password will result in an `SMTPAuthenticationError` or similar.
- gotcha Providing your main Gmail password directly in the script is a security risk and is discouraged. yagmail prefers using `keyring` for secure storage or OAuth2.
- gotcha When sending HTML content, newline characters (\n) in plain strings might be automatically converted to `<br>` tags. This behavior can be unexpected if you're mixing plain text and HTML.
- gotcha Installation with `pip install yagmail[all]` can sometimes fail due to `keyring` or `dkimpy` dependencies, especially on certain operating systems or Python environments.
- gotcha When using `yagmail.SMTP()`, if no explicit 'to' argument is provided in `send()`, the email defaults to being sent to the sender's own address.
Install
-
pip install yagmail[all] -
pip install yagmail
Imports
- SMTP
from yagmail import SMTP
Quickstart
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}')