To send an email with Python, you can use the built-in smtplib
module. Here's an example of how to send an email using a Gmail account:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Email configuration
sender_email = 'your_email@gmail.com'
receiver_email = 'recipient_email@example.com'
subject = 'Hello from Python!'
message = 'This is a test email sent from Python.'
# SMTP server configuration (for Gmail)
smtp_server = 'smtp.gmail.com'
smtp_port = 587
username = 'your_email@gmail.com'
password = 'your_password'
# Create the email message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
# Create the SMTP connection and send the email
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.send_message(msg)
print('Email sent successfully!')
except Exception as e:
print('Error sending email:', str(e))
finally:
server.quit()
Make sure to replace your_email@gmail.com
with your actual Gmail address and your_password
with your Gmail password or an app-specific password if you have two-factor authentication enabled.
This example demonstrates a basic email sending functionality. You can modify the subject
, message
, sender_email
, and receiver_email
variables to customize the content of the email. Additionally, you can include attachments or use HTML formatting by extending the MIME message.
Please note that some email providers may have different SMTP server addresses and ports, so you might need to adjust those values accordingly if you are not using Gmail.