View Categories

How to configuration SMTP in Python

1 min read

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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *

Privacy Settings
We use cookies to enhance your experience while using our website. If you are using our Services via a browser you can restrict, block or remove cookies through your web browser settings. We also use content and scripts from third parties that may use tracking technologies. You can selectively provide your consent below to allow such third party embeds. For complete information about the cookies we use, data we collect and how we process them, please check our Privacy Policy
Youtube
Consent to display content from Youtube
Vimeo
Consent to display content from Vimeo
Google Maps
Consent to display content from Google
Spotify
Consent to display content from Spotify
Sound Cloud
Consent to display content from Sound
SIGN UP NOW