E-Mail mit Dateianhang über SMTP in Python senden
English
Deutsch
Dieses Beispiel zeigt, wie man in Python eine E-Mail mit einem Anhang sendet, wobei der Anhang aus einer Datei auf dem Dateisystem gelesen wird:
send_email_attachment.py
#!/usr/bin/env python3
import smtplib
import mimetypes
from email.message import EmailMessage
# Nachricht erstellen und Textinhalt setzen
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# Textinhalt setzen
msg.set_content('Please see attached file')
def attach_file_to_email(email, filename):
"""Datei mit filename an E-Mail-Nachricht anhängen"""
with open(filename, 'rb') as fp:
file_data = fp.read()
maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
email.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=filename)
# Dateien anhängen
attach_file_to_email(msg, "myfile.pdf")
def send_mail_smtp(mail, host, username, password):
s = smtplib.SMTP(host)
s.starttls()
s.login(username, password)
s.send_message(mail)
s.quit()
send_mail_smtp(msg, 'smtp.my-domain.com', 'sender@domain.com', 'sae7ooka0S')Die Hilfsfunktionen in diesem Code sind:
email_utils.py
import smtplib
import mimetypes
def attach_file_to_email(email, filename):
"""Datei mit filename an E-Mail-Nachricht anhängen"""
with open(filename, 'rb') as fp:
file_data = fp.read()
maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
email.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=filename)
def send_mail_smtp(mail, host, username, password):
s = smtplib.SMTP(host)
s.starttls()
s.login(username, password)
s.send_message(mail)
s.quit()E-Mail so initialisieren:
create_email_msg.py
# Nachricht erstellen und Textinhalt setzen
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# Textinhalt setzen
msg.set_content('Please see attached file')und dann die Datei so anhängen:
attach_example.py
attach_file_to_email(msg, "myfile.pdf")und die E-Mail senden mit
send_email_example.py
send_mail_smtp(msg, 'smtp.my-domain.com', 'sender@domain.com', 'sae7ooka0S')Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow