Send email gmail python

Here is an example of how to send an email using Python and Gmail:

import smtplib
from email.mime.text import MIMEText

# Define the email settings
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "[email protected]"
PASSWORD = "your_password"

# Define the email message
SUBJECT = "Test email from Python"
BODY = "This is a test email sent from Python."

# Create a text message
msg = MIMEText(BODY)
msg["Subject"] = SUBJECT
msg["From"] = FROM_EMAIL
msg["To"] = "[email protected]"

# Connect to the SMTP server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(FROM_EMAIL, PASSWORD)

# Send the email
server.sendmail(FROM_EMAIL, "[email protected]", msg.as_string())

# Close the SMTP connection
server.quit()

This code uses the smtplib library to connect to the Gmail SMTP server, and the email.mime.text library to create a text message. You'll need to replace [email protected] and your_password with your actual Gmail address and password.

Note that you'll also need to allow less secure apps to access your Gmail account. You can do this by going to your Google Account settings, clicking on "Security", and then toggling the switch next to "Less secure app access" to the "On" position.

Also, be aware that storing your password in plain text is not secure. You may want to consider using a more secure method, such as using environment variables or a secrets manager.

You can also use the yagmail library which is a wrapper around smtplib and makes it easier to send emails.

import yagmail

yag = yagmail.SMTP(FROM_EMAIL, PASSWORD)
yag.send("[email protected]", SUBJECT, BODY)

Make sure to install the yagmail library by running pip install yagmail

You can also use the gmail-api library which is a Python client library for the Gmail API.

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

creds = Credentials.get_credentials()
service = build('gmail', 'v1', credentials=creds)

message = MIMEText(BODY)
message["Subject"] = SUBJECT
message["From"] = FROM_EMAIL
message["To"] = "[email protected]"

raw_message = base64.urlsafe_b64encode(message.as_bytes())
raw_message = raw_message.decode()

body = {'raw': raw_message}

service.users().messages().send(userId='me', body=body).execute()

Make sure to install the google-api-python-client and google-auth libraries by running pip install google-api-python-client google-auth

Please note that you need to have the GOOGLE_APPLICATION_CREDENTIALS environment variable set with the path to your JSON key file to use the gmail-api library.