Send email in python
Here is an example of how to send an email using Python:
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()
This code uses the smtplib
library to connect to the SMTP server and send the email. The MIMEText
class is used to create the email message, and the sendmail
method is used to send the email.
You'll need to replace the placeholders ([email protected]
, your_password
, [email protected]
) with your actual email address, password, and the recipient's email address.
You can also use other libraries such as yagmail
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)
You can also use email
library which is a part of Python's standard library
import email
from email.mime.text import MIMEText
msg = MIMEText(BODY)
msg["Subject"] = SUBJECT
msg["From"] = FROM_EMAIL
msg["To"] = "[email protected]"
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.sendmail(FROM_EMAIL, "[email protected]", msg.as_string())
Please note that you need to enable less secure apps in your email account settings to use this code.
Also, you can use python-email
library which is a wrapper around email
library and makes it easier to send emails.
import python_email
msg = python_email.Message(BODY)
msg["Subject"] = SUBJECT
msg["From"] = FROM_EMAIL
msg["To"] = "[email protected]"
server = python_email.SMTP(SMTP_SERVER, SMTP_PORT)
server.sendmail(FROM_EMAIL, "[email protected]", msg.as_string())