Wie kann man in Python eine E-Mail mit Anhang per SMTP versenden?

This post is also available in: enEnglish (Englisch)

Dieses Bespiel zeigt, wie man in Python eine E-Mail mit Anhang versenden kann. Der Anhang wird direkt aus einer Datei gelesen.

#!/usr/bin/env python3
import smtplib
import mimetypes
from email.message import EmailMessage

# E-Mail-Objekt initialisieren und Nachrichtentext setzen:
msg = EmailMessage()
msg['Subject'] = 'Diese E-mail enthält einen Anhang'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Set text content
msg.set_content('Please see attached file')

def attach_file_to_email(email, filename):
    """Attach a file identified by filename, to an email message"""
    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)

# Anhang 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(msg)
    s.quit()

# E-Mail per SMTP senden
send_mail_smtp(msg, 'smtp.domain.com', '[email protected]', 'sae7ooka0S')

Das oben gezeigte Skript benutzt die Folgenden Funktionen:

import smtplib
import mimetypes

def attach_file_to_email(email, filename):
    """Attach a file identified by filename, to an email message"""
    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(msg)
    s.quit()

Initalisiere das E-Mail-Object wie Folgt:

# E-Mail-Objekt initialisieren und Nachrichtentext setzen:
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Set text content
msg.set_content('Please see attached file')

und hänge dann die Datei so an:

attach_file_to_email(msg, "myfile.pdf")

Danach kannst du die E-Mail so per SMTP versenden:

send_mail_smtp(msg, 'smtp.my-domain.com', '[email protected]', 'sae7ooka0S')