0 Pluspunkte 0 Minuspunkte

Wie kann ich mit SMTPLib in Python eine Email an mehrere Empfänger senden?

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

# Email configuration
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_password'

# Email content
from_email = 'your_email@example.com'
to_email = 'recipient@example.com'
subject = 'Test Email'
body = 'This is a test email sent using Python.'

# Create a MIME object
message = MIMEMultipart()
message['From'] = from_email
message['To'] = to_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))

# Send the email
try:
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()  # Secure the connection
        server.login(smtp_username, smtp_password)  # Log in to the server
        server.sendmail(from_email, to_email, message.as_string())  # Send the email
    print('Email sent successfully.')
except Exception as e:
    print(f'Error: {e}')
bezieht sich auf eine Antwort auf: SMTP Email senden mit Python
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Du kannst die Empfänger durch ein Comma getrennt angeben. In deinem Beispiel:

to_emails = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com'] 

Danach joinst du das Array zu einem Comma separierten String.

message['To'] = ', '.join(to_emails)

Hier der gesamte Code:

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

# Email configuration
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_password'

# Email content
from_email = 'your_email@example.com'
to_emails = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com']
subject = 'Test Email to Multiple Recipients'
body = 'This is a test email sent to multiple recipients using Python.'

# Create a MIME object
message = MIMEMultipart()
message['From'] = from_email
message['To'] = ', '.join(to_emails)
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))

# Send the email
try:
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()  # Secure the connection
        server.login(smtp_username, smtp_password)  # Log in to the server
        server.sendmail(from_email, to_emails, message.as_string())  # Send the email
    print('Email sent successfully to multiple recipients.')
except Exception as e:
    print(f'Error: {e}')
von (542 Punkte)