Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
E-Mail-Nachrichten werden als HTTP-Anfragen mit MIME-Daten an die Anwendung gesendet. Zur Verarbeitung eingehender E-Mail-Nachrichten ordnen Sie in der Anwendungskonfiguration E-Mail-Adressen den Skript-Handlern zu und nehmen die Handler anschließend in den Code der Anwendung auf.
Eingehende E-Mails generieren HTTP-Anfragen, die an die entsprechenden Skripts weitergeleitet werden. Die Skripts, die die eingehende E-Mails behandeln, müssen sich in Ihrem Standarddienst befinden.
Anwendung für den Empfang von E-Mails konfigurieren
Wenn Sie eine neue Anwendung erstellen, werden eingehende E-Mails standardmäßig deaktiviert. Um die eingehenden E-Mails zu aktivieren, müssen Sie die Datei app.yaml in Ihrem Standarddienst ändern.
Fügen Sie den inbound_services-Abschnitt hinzu, der den Dienst für eingehende E-Mails aktiviert.
Beispiel:
inbound_services:-mail
Wenn Sie eingehende E-Mails nicht aktivieren, indem Sie diesen Abschnitt in die Konfigurationsdatei einschließen, werden eingehende E-Mails deaktiviert und E-Mail-Nachrichten ignoriert, die an die Anwendung gesendet werden.
Fügen Sie Zuordnungen zwischen URL-zugeordneten E-Mail-Adressen und Skript-Handlern hinzu.
Beim Standarddienst hat die E-Mail-Adresse zum Empfangen von E-Mails das folgende Format:
[STRING]@[Google Cloud projectID].appspotmail.com
Bei nicht standardmäßigen Diensten hat die E-Mail-Adresse folgendes Format:
E-Mail-Nachrichten werden als HTTP POST-Anfragen über die folgende URL an die Anwendung gesendet. Dabei steht [ADDRESS] für eine vollständige E-Mail-Adresse, einschließlich des Domainnamens:
/_ah/mail/[ADDRESS]
Um eingehende E-Mails in Ihrer App zu verarbeiten, ordnen Sie E-Mail-URLs den Handlern in der Datei app.yaml zu:
Im obigen Beispiel entspricht /_ah/mail/.+ allen E-Mails, die an die App adressiert sind. Sie können auch mehrere Handler für verschiedene E-Mail-Adressen einrichten, wie im folgenden Beispiel gezeigt:
Die URLs der eingehenden E-Mail-Nachrichten werden absteigend mit dieser Liste abgeglichen. Sollte also die URL einer E-Mail-Nachricht mit mehreren Mustern übereinstimmen, so wird der erste übereinstimmende Handler ausgeführt. Dadurch können Sie als letzte Zuordnung einen "Catchall"-Handler einfügen. Die Handler werden im Standardmodul (oder in der Anwendungsversion) ausgeführt.
Eingehende E-Mails verarbeiten
Das Python SDK definiert InboundMailHandler, eine webapp-Klasse für die Verarbeitung eingehender E-Mails. InboundMailHandlerbefindet sich im Paket google.appengine.ext.webapp.mail_handlers.
Mithilfe von InboundMailHandler:
Erstellen Sie eine Unterklasse für InboundMailHandler und überschreiben Sie die Methode receive().
Rufen Sie an receive() -Methode mit einem -Argument der -Klasse InboundEmailMessage , definiert durch das Python SDK.
Sie können beispielsweise eine Instanz von InboundEmailMessage wie folgt erstellen:
importloggingfromgoogle.appengine.ext.webapp.mail_handlersimportInboundMailHandlerimportwebapp2classLogSenderHandler(InboundMailHandler):defreceive(self,mail_message):logging.info("Received a message from: "+mail_message.sender)
InboundMailHandler enthält eine Convenience-Klassenmethode vom Typ mapping(), die ein Paar zurückgibt, das mit allen eingehenden E-Mail-Adressen an den E-Mail-Handler übereinstimmt. Sie können es natürlich in jeder abgeleiteten Klasse von InboundMailHandler aufrufen, die Sie codieren:
Das InboundEmailMessage -Objekt (mail_message in diesem Beispiel) enthält die E-Mail-Nachricht. Die Methode bodies() gibt die Textkörper in der Nachricht zurück. Wenn Sie bodies() ohne Argumente aufrufen, wird ein Iterator zurückgegeben, der zuerst HTML-Textkörper und dann Nur-Text-Textkörper liefert. Wenn Sie nur HTML oder nur Text verwenden möchten, übergeben Sie ein Argument an bodies():
Das InboundEmailMessage-Objekt enthält Attribute für den Zugriff auf andere Nachrichtenfelder:
subjectenthält den Betreff der Nachricht.
senderist die E-Mail-Adresse des Senders, z. B. "Nobody <nobody@example.com>".
to ist eine durch Kommas getrennte Liste der primären Empfänger der Nachricht, z.B. "Joe <joe@example.com>, Bill <bill@example.com>".
cc enthält eine durch Kommas getrennte Liste der Cc-Empfänger, z.B. "Joe <joe@example.com>, Bill <bill@example.com>".
date gibt das Datum der Nachricht zurück.
attachments ist eine Liste von Attachment -Objekten, möglicherweise leer.
original ist die vollständige Nachricht, einschließlich der Daten, die in den anderen Feldern wie E-Mail-Headern nicht als Python- email.message.Message verfügbar gemacht werden.
Eingehende Nachrichten mit lokalem Entwicklungsserver simulieren
Nachdem Sie die Anwendung für die Verarbeitung eingehender E-Mails eingerichtet haben, können Sie mithilfe der Entwicklungsserverkonsole eingehende E-Mail-Nachrichten simulieren:
Greifen Sie als Administrator auf den Entwicklungsserver zu. Dazu rufen Sie http://localhost:8080/console auf und wählen Als Administrator anmelden aus.
Klicken Sie im Menü des Entwicklungsservers auf Eingehende Mail.
Füllen Sie das angezeigte Formular aus und klicken Sie auf E-Mail senden.
Weitere Informationen, einschließlich zum Ausführen des Entwicklungsservers, finden Sie unter Python-Entwicklungsserver.
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-09-04 (UTC)."],[[["\u003cp\u003eIncoming emails to the app are processed as HTTP requests with MIME data, requiring configuration to associate email addresses with specific script handlers.\u003c/p\u003e\n"],["\u003cp\u003eTo enable incoming email, the \u003ccode\u003einbound_services\u003c/code\u003e section with the \u003ccode\u003e- mail\u003c/code\u003e parameter must be added to the \u003ccode\u003eapp.yaml\u003c/code\u003e file in the default service.\u003c/p\u003e\n"],["\u003cp\u003eEmail URLs, formatted as \u003ccode\u003e/_ah/mail/[ADDRESS]\u003c/code\u003e, must be mapped to handlers in the \u003ccode\u003eapp.yaml\u003c/code\u003e file to route incoming emails to the correct script.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eInboundMailHandler\u003c/code\u003e class, which must be subclassed, should be used to manage incoming emails, and its \u003ccode\u003ereceive()\u003c/code\u003e method should be overridden to process email messages.\u003c/p\u003e\n"],["\u003cp\u003eThe development server allows simulating incoming emails for testing purposes through its console, which can be used to test the email handlers.\u003c/p\u003e\n"]]],[],null,["# Receiving Email\n\nEmail messages sent to your app are implemented as HTTP requests containing MIME\ndata. To process incoming email messages, you associate email addresses with\nscript handlers in your app configuration, then include the handlers in your\napp's code.\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nIncoming email generates HTTP requests, which are passed to the appropriate\nscripts. The scripts that handle the incoming email must reside in your default\nservice.\n\nFor more information on the Mail service, see the\n[Mail API Overview](/appengine/docs/legacy/standard/python/mail).\n\nConfiguring your application to receive email\n---------------------------------------------\n\nWhen you create a new app, incoming email is disabled by default. To enable the\nincoming email, you must modify your `app.yaml` file in your default service.\n\n1. Add an `inbound_services` section that enables the incoming email service.\n For example:\n\n inbound_services:\n - mail\n\n If you don't enable incoming email by including this section in your\n configuration file, then incoming email is disabled, and email messages sent\n to the app are ignored.\n2. Add mappings that associate URL-mapped email addresses with script handlers.\n\n For the [default service](/appengine/docs/legacy/standard/python/configuration-files#the_default_service), the email address for receiving email has the following format: \n\n [STRING]@[Google Cloud project ID].appspotmail.com\n\n For non-default services, the email address has the following format: \n\n [STRING]@[servicename]-dot-[Google Cloud project ID].appspotmail.com\n\n Email messages are sent to your app as HTTP POST requests using the\n following URL, where \u003cvar translate=\"no\"\u003e[ADDRESS]\u003c/var\u003e is a full email address, including\n domain name: \n\n /_ah/mail/[ADDRESS]\n\n To handle incoming email in your app, map email URLs to handlers in the\n `app.yaml` file: \n\n - url: /_ah/mail/.+\n script: handle_incoming_email.app\n login: admin\n\n In the above example, `/_ah/mail/.+` matches all email addressed to the app.\n If you prefer, you can set up multiple handlers for different email\n addresses, as in the following example: \n\n - url: /_ah/mail/owner@.*your_app_id\\.appspotmail\\.com\n script: handle_owner.app\n login: admin\n - url: /_ah/mail/support@.*your_app_id\\.appspotmail\\.com\n script: handle_support.app\n login: admin\n - url: /_ah/mail/.+\n script: handle_catchall.app\n login: admin\n\n URLs of incoming email messages are matched to this list from first to last,\n so if an email message URL matches more than one pattern, the first matching\n handler will be the one executed. This allows you to include a \"catchall\"\n handler as the last mapping. The handlers run in the default module (or\n application version).\n\nHandling incoming email\n-----------------------\n\nThe Python SDK defines `InboundMailHandler`, a webapp class for handling\nincoming email. `InboundMailHandler` is in the\n[`google.appengine.ext.webapp.mail_handlers`](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.webapp.mail_handlers)\npackage.\n\nTo use `InboundMailHandler`:\n\n1. Create a subclass for `InboundMailHandler` and override the `receive()` method.\n2. Call the `receive()` method with an argument of class `InboundEmailMessage`, defined by the Python SDK.\n\nFor example, you can create an instance of `InboundEmailMessage` like this: \n\n import logging\n\n from google.appengine.ext.webapp.mail_handlers import InboundMailHandler\n import webapp2\n\n\n class LogSenderHandler(InboundMailHandler):\n def receive(self, mail_message):\n logging.info(\"Received a message from: \" + mail_message.sender)\n\n| **Note:** Even if you are using the [webapp2](/appengine/docs/legacy/standard/python/tools/webapp2) framework, you still need to use the `InboundMailHandler` class provided by the old `webapp` framework. This handler is specific to the App Engine mail service, whereas webapp2 is provided by a third party.\n\n`InboundMailHandler` contains a `mapping()` convenience class method that\nreturns a pair matching all incoming email addresses to the mail handler and of\ncourse you can call it on any subclass of `InboundMailHandler` you code: \n\n app = webapp2.WSGIApplication([LogSenderHandler.mapping()], debug=True)\n\nThe `InboundEmailMessage` object (`mail_message` in this example) contains the\nemail message. Its `bodies()` method returns the bodies within the message. If\nyou call `bodies()` without arguments, it returns an iterator that yields HTML\nbodies first, then plain text bodies. If you want just HTML or just plain text,\nyou can pass an argument to `bodies()`: \n\n plaintext_bodies = mail_message.bodies('text/plain')\n html_bodies = mail_message.bodies('text/html')\n\n for content_type, body in html_bodies:\n decoded_html = body.decode()\n # ...\n\nThe `InboundEmailMessage` object includes attributes to access other message\nfields:\n\n- `subject` contains the message subject.\n- `sender` is the sender's address e.g. `\"Nobody \u003cnobody@example.com\u003e\"`.\n- `to` is a comma-separated list of the message's primary recipients e.g. `\"Joe \u003cjoe@example.com\u003e, Bill \u003cbill@example.com\u003e\"`.\n- `cc` contains a comma-separated list of the cc recipients e.g. `\"Joe \u003cjoe@example.com\u003e, Bill \u003cbill@example.com\u003e\"`.\n- `date` returns the message date.\n- `attachments` is a list of [`Attachment`](/appengine/docs/legacy/standard/python/refdocs/google.appengine.api.mail#google.appengine.api.mail.Attachment) objects, possibly empty.\n- `original` is the complete message, including data not exposed by the other fields such as email headers, as a Python [`email.message.Message`](http://docs.python.org/library/email.message.html).\n\nSimulating incoming messages with the local development server\n--------------------------------------------------------------\n\nOnce you set up your app to handle incoming email, you can use the\ndevelopment server console to simulate incoming email messages:\n\n1. Access the development server as an administrator by going to \u003chttp://localhost:8080/console\u003e and selecting **Sign in as administrator**.\n2. In the development server, click **Inbound Mail** in the navigation.\n3. Fill out the form that appears, and click **Send Email**.\n\n To learn more, including how to get the development server running, see\n [the Python Development Server](/appengine/docs/legacy/standard/python/tools/using-local-server)."]]