Introduction
The provided Python code demonstrates how to send emails using the SMTP protocol. It uses the smtplib
module to establish a connection to an SMTP server, and the email
module to construct the email message. The code allows you to specify custom SMTP options such as the SMTP server address, port number, username, and password.
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(sender, receiver, subject, message, smtp_server, smtp_port, smtp_username, smtp_password): # Create a multipart message msg = MIMEMultipart() msg['From'] = sender msg['To'] = receiver msg['Subject'] = subject # Add the message to the body of the email msg.attach(MIMEText(message, 'plain')) try: # Create an SMTP object with smtplib.SMTP(smtp_server, smtp_port) as smtp: # Start the TLS encryption smtp.starttls() # Login to the SMTP server smtp.login(smtp_username, smtp_password) # Send the email smtp.send_message(msg) print("Email sent successfully!") except smtplib.SMTPException as e: print("Error: unable to send email.") print(e) # Example usage sender = 'sender@example.com' receiver = 'receiver@example.com' subject = 'Hello from SMTP!' message = 'This is a test email.' smtp_server = 'smtp.example.com' smtp_port = 587 smtp_username = 'your_smtp_username' smtp_password = 'your_smtp_password' send_email(sender, receiver, subject, message, smtp_server, smtp_port, smtp_username, smtp_password)
Conclusion: This code snippet provides a basic framework for sending emails using SMTP in Python. By customizing the sender, receiver, subject, message, and SMTP options, you can adapt it to your specific requirements. Remember to replace the placeholder values in the example usage section with your actual email addresses and SMTP credentials. Feel free to expand upon this code to include additional functionality or error handling, as needed.