Send smtp email

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

import smtplib

# Define the email settings
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "[email protected]"
PASSWORD = "your_password"
TO_EMAIL = "[email protected]"
SUBJECT = "Test Email"
BODY = "This is a test email sent using Python."

# Create a secure connection to the SMTP server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(FROM_EMAIL, PASSWORD)

# Send the email
msg = f"Subject: {SUBJECT}\n\n{BODY}"
server.sendmail(FROM_EMAIL, TO_EMAIL, msg)

# Close the connection
server.quit()

This code uses the smtplib library to connect to the SMTP server, login with your email and password, and send the email.

You can also use the email library to create a more complex email message with attachments, HTML content, etc.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Define the email settings
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "[email protected]"
PASSWORD = "your_password"
TO_EMAIL = "[email protected]"
SUBJECT = "Test Email"
BODY = "This is a test email sent using Python."

# Create a secure connection to the SMTP server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(FROM_EMAIL, PASSWORD)

# Create a message
msg = MIMEMultipart()
msg["From"] = FROM_EMAIL
msg["To"] = TO_EMAIL
msg["Subject"] = SUBJECT
msg.attach(MIMEText(BODY, "plain"))

# Send the email
server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())

# Close the connection
server.quit()

You can also use the yagmail library which is a wrapper around smtplib and email libraries, it's more easy to use and has more features.

import yagmail

# Define the email settings
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "[email protected]"
PASSWORD = "your_password"
TO_EMAIL = "[email protected]"
SUBJECT = "Test Email"
BODY = "This is a test email sent using Python."

# Create a yagmail object
yag = yagmail.SMTP(FROM_EMAIL, PASSWORD)

# Send the email
yag.send(TO_EMAIL, SUBJECT, BODY)

# Close the connection
yag.close()

Please note that you need to replace the placeholders ([email protected], your_password, [email protected]) with your actual email and password.

Also, you need to allow less secure apps to access your email account, you can do this by going to your email account settings and enabling the option.

It's also important to note that this is just an example, you should not hardcode your email and password in your code, you should use a secure way to store and retrieve your credentials.