Skip to content

python send email

To send an email in Python, you can use the built-in smtplib library to connect to an SMTP server and send the email. You’ll also need the email library to create and format the email message. Here’s a basic example of how to send an email using Python:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Email configuration
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
receiver_email = 'receiver_email@example.com'
subject = 'Subject of the email'
message = 'This is the email body.'

# Create a message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject

# Attach the message body
msg.attach(MIMEText(message, 'plain'))

# Connect to the SMTP server (in this example, using Gmail)
try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()  # Secure the connection
    server.login(sender_email, sender_password)  # Login to your email account

    # Send the email
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)

    print('Email sent successfully!')
except Exception as e:
    print(f'Email could not be sent. Error: {str(e)}')
finally:
    server.quit()  # Quit the server

Replace 'your_email@gmail.com', 'your_password', 'receiver_email@example.com', 'Subject of the email', and 'This is the email body.' with your own email credentials, the recipient’s email address, the subject of the email, and the email message body.

Please note that using your email and password directly in your code is not recommended for security reasons. Instead, you should consider using environment variables or a configuration file to store your email credentials securely. Additionally, you may need to enable “less secure apps” or generate an “app password” in your email account settings if you’re using Gmail or a similar service that requires it.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)