E-Mails senden aus Python heraus

Aktuell benötige ich Funktionalitäten in Python, um E-Mails automatisch versenden zu lassen. Über Chat-GPT habe ich mir passenden Code basteln lassen, der recht gut funktioniert.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
def send_email():
    # Email content
    sender_email = 'YOUR_EMAIL_ADDRESS'
    password = 'YOUR_PASSWORD'
    recipient_email = 'RECIPIENT_EMAIL_ADDRESS'
    subject = 'SUBJECT'
    body = 'EMAIL_BODY'
 
    # Create a multipart message and set headers
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient_email
    message['Subject'] = subject
 
    # Add body to email
    message.attach(MIMEText(body, 'plain'))
 
    try:
        # Connect to SMTP server (for Gmail use 'smtp.gmail.com', for others, refer to your provider's settings)
        smtp_server = smtplib.SMTP('smtp.yourprovider.com', 587)
        smtp_server.starttls()  # Enable encryption for security
        smtp_server.login(sender_email, password)
 
        # Send email
        smtp_server.sendmail(sender_email, recipient_email, message.as_string())
        print("Email sent successfully!")
 
        # Close the connection
        smtp_server.quit()
    except Exception as e:
        print(f"Error: {e}")
        print("Email was not sent.")
 
# Call the function to send the email
send_email()

Falls der SMTP-Server keine Authentifizierung braucht, dann reicht auch das folgende

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
def send_email():
    # Email content
    sender_email = 'YOUR_EMAIL_ADDRESS'
    recipient_email = 'RECIPIENT_EMAIL_ADDRESS'
    subject = 'SUBJECT'
    body = 'EMAIL_BODY'
 
    # Create a multipart message and set headers
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient_email
    message['Subject'] = subject
 
    # Add body to email
    message.attach(MIMEText(body, 'plain'))
 
    try:
        # Connect to SMTP server
        smtp_server = smtplib.SMTP('smtp.yourprovider.com')  # Replace with your SMTP server address
        smtp_server.sendmail(sender_email, recipient_email, message.as_string())
        print("Email sent successfully!")
 
        # Close the connection
        smtp_server.quit()
    except Exception as e:
        print(f"Error: {e}")
        print("Email was not sent.")
 
# Call the function to send the email
send_email()

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website