You can send emails using Python’s built-in smtplib
library, which supports the Simple Mail Transfer Protocol (SMTP). Here’s a step-by-step guide:
Steps to Send an Email:
- Import Libraries: Use
smtplib
for sending emails andemail
library to format the email. - Set Up SMTP Server: Connect to your email provider’s SMTP server.
- Log In: Authenticate using your email and password.
- Compose the Email: Use the
email.message
module to craft the email. - Send the Email: Use
smtplib
to send the email
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # Email details sender_email = "[email protected]" receiver_email = "[email protected]" password = "your_email_password" # Create the email subject = "Test Email" body = "This is a test email sent using Python." # Set up the MIME message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject # Attach the body message.attach(MIMEText(body, "plain")) # Connect to the SMTP server try: with smtplib.SMTP("smtp.gmail.com", 587) as server: # Gmail SMTP server server.starttls() # Secure the connection server.login(sender_email, password) # Log in to the server server.sendmail(sender_email, receiver_email, message.as_string()) # Send the email print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {e}")
Key Points:
-
SMTP Server and Port:
- Gmail:
smtp.gmail.com
and port587
- Outlook:
smtp.office365.com
and port587
- Yahoo:
smtp.mail.yahoo.com
and port587
- Gmail:
-
Enable Access for Less Secure Apps: Some email providers require you to enable access for less secure apps or use app-specific passwords for SMTP.
-
Secure Connections:
- Use
server.starttls()
for encrypted connections. - Consider using
smtplib.SMTP_SSL()
for secure connection on port465
.
- Use