Send email python gmail

Here is an example of how to send an email using Python with 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"
BODY = "This is a test email sent using 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()

Make sure to replace [email protected] and your_password with your actual Gmail email and password.

Also, note that you need to allow less secure apps to access your Gmail account. You can do this by going to your Google Account settings and enabling the "Less secure app access" option.

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

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 in your terminal.

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

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

# Define the email settings
creds = Credentials.get_credentials()
service = build('gmail', 'v1', credentials=creds)

# Define the email message
message = {
    'to': '[email protected]',
    'from': FROM_EMAIL,
    'subject': SUBJECT,
    'body': BODY
}

# Send the email
service.users().messages().send(userId='me', body=message).execute()

Make sure to install the google-api-python-client library by running pip install google-api-python-client in your terminal.

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.