Send email python smtp
Here is an example of how to send an email using Python with the smtplib
library:
import smtplib
from email.mime.text import MIMEText
# Define the email message
subject = "Test email from Python"
body = "This is a test email sent from Python using smtplib."
from_addr = "[email protected]"
to_addr = "[email protected]"
# Create a text message
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr
# Set up the SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587) # Replace with your SMTP server
server.starttls()
server.login(from_addr, "your_email_password") # Replace with your email password
# Send the email
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
This code creates a text message with a subject, body, from address, and to address, and then sends it using the smtplib
library. You'll need to replace the placeholders (your_email_address
, your_email_password
, smtp.gmail.com
, and 587
) with your actual email address, password, and SMTP server settings.
Here are some notes on the code:
- The
smtplib
library is part of the Python standard library, so you don't need to install any additional packages. - The
MIMEText
class is used to create a text message. You can also useMIMEImage
orMIMEApplication
to send images or binary files. - The
starttls()
method is used to establish a secure connection to the SMTP server. This is recommended to prevent eavesdropping and tampering with the email. - The
login()
method is used to authenticate with the SMTP server using your email address and password. - The
sendmail()
method is used to send the email. The first argument is the from address, the second argument is the to address, and the third argument is the email message as a string.
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('[email protected]', 'your_email_password')
yag.send('[email protected]', 'Test email from Python', 'This is a test email sent from Python using yagmail.')
Make sure to replace the placeholders with your actual email address and password.