Überprüfung des Empfängers: Beispiele für E-Mail-Verifizierungscodes

Überprüfung des Empfängers: Beispiele für E-Mail-Verifizierungscodes

Validierung des Empfängers: E-Mail Verification Code Examples

Jul 8, 2020

Herausgegeben von

Herausgegeben von

Bird

Bird

-

Kategorie:

Kategorie:

E-Mail

Email

Ready to see Bird
in action?

Ready to see Bird
in action?

Überprüfung des Empfängers: Beispiele für E-Mail-Verifizierungscodes

SparkPost Recipient Validation is now available both for existing SparkPost customers and for new, non-sending customers. It uses powerful data-driven analysis on billions of bounce, delivery, and engagement events daily to train our algorithm, bringing you one of the most powerful data-driven email validation tools on the market, so you can send emails smarter.

Dieser Artikel explains how you can get the most out of the data you’ll receive back on each validated recipient – you’ll see we classify addresses to be “valid”, “risky”, “neutral”, “undeliverable”, and “typo”. We give you a “reason” code and also a “did_you_mean” for known address typos.


API-Anfragen

In the SparkPost web app, you can drag & drop an entire list for validation. You can also use die API to validate single addresses, so you can build validation right into your address entry workflow.

A while back we came up with a Python-Befehlszeilen-Tool using this API. We talked over what we should do for andere languages – and here we are! Let’s get started.

This Github-Repository-Ordner has working Recipient Validation API call examples in around a dozen different languages. We try to cover the die beliebtesten anwendbaren Sprachen.

Alle diese Beispiele lassen sich auf die gleiche Weise durcharbeiten:

  • Pick up your key from environment variable SPARKPOST_API_SCHLÜSSEL

  • Make an API call to /api/v1/empfänger-validierung/single/to validate a recipient

  • eine Antwortzeichenfolge zurückerhalten, die JSON-formatierte Daten mit dem Ergebnis enthält

  • Drucken Sie das Ergebnis aus

SparkPost has Bibliotheken for some, but not all of the languages covered here. We chose to write these examples “native” instead, so we could a) cover more languages, b) show how simple the underlying code can be, and c) enable you to see clearly the similarities and differences between languages.


Bash / Locke

Dies gewinnt den Preis für den kürzesten Code - es wird einfach das Kommandozeilentool "curl" verwendet, um die Anfrage zu stellen und die Antwort direkt in das Terminal zu drucken. Wie Sie sehen, ist die Ausgabe eine Zeichenkette, die JSON enthält; wir analysieren die einzelnen Ergebnisattribute nicht.


PHP

Trusty PHP has a few different Wege to make HTTPS API calls. Here we chose to use curl_setopt and curl_exec. (https://www.php.net/manual/en/function.curl-exec.php)

If you prefer HTTP_Request2 or pecl_http, then Postman has a built-in code generator that you can use to create similar examples – just set up a working GET request and use the “Code” button.


Python

This uses the popular requests module, which is high-level and therefore easy to use. This example checks the returned status code, converts the results JSON back into a Python dictionary object, and prints the resulting object rather than just a string.

If you prefer the built-in http.client library, Postman can generate code for that too; it’s not much longer.


Node.js

There are viele verschiedene node.js HTTP(S) libraries. I started with the older request package (using a callback function) but it’s deprecated and no longer actively maintained.  I chose the newer axios package (using verspricht). 

Postman can also give you a Javascript native example and Unirest, in case you prefer those.

Da dieser Code Zugriff auf Ihren API-Schlüssel benötigt, empfehlen wir dringend, unsere API von der Server-Seite aus aufzurufen, niemals von der Client-Seite (Browser/Mobilgerät).


Weiter

Go strives toward a philosophy of “one good way” to do something; in this case, using the built-in “batteries included” libraries net/http, encoding/json and others.

Die length is due mostly zum explicit error checking clauses if err != nil {} everywhere (keine Ausnahmen LOL).

Wir deklarieren auch die Struktur des Ergebnisobjekts mit Feld-Tags, damit wir die zurückgegebene JSON-Zeichenkette "entschachteln" können. Wir überlagern die Tags "Ergebnisse" und "Fehler", um beide Arten der Rückgabe zu ermöglichen.

Ich mag die Geschwindigkeit, die Typsicherheit und die Klarheit von Go, auch wenn der Code länger ist als unsere vorherigen Beispiele.


C#

I’m less familiar with C# – to me, it looks quite Java-like, rather than C-like. I was able to put this together following examples shown in the request library System.Net.Http.

Postman can auto-generate example code using RestSharp, if you prefer that.


Rubinrot

This was my first attempt at Ruby code; I used the Netz::http library, and followed dieses Beispiel (which turns out to be very close zum code that Postman auto-generates).

I ran into one language / library oddity that’s worth explaining. Just setting up using a URI that begins “https://” is not enough, you have to specifically set http.use_ssl = true

Ohne dies wird Ihr Code eine Anfrage auf Port 443 versuchen - aber ohne SSL/TLS (d.h. in plain), und SparkPost wird sich zu Recht weigern, die Anfrage zu autorisieren. Versuchen Sie das nicht zu Hause, denn Ihr API-Schlüssel steht im Authorization-Header. Diese Sprach-/Bibliotheksfunktion kam mir unsicher vor.


Java

I’ve not written any serious Java before, but it was easy to piece this together by following the general approach used in the SparkPost-Bibliothek for other GET calls.

Incidentally, using VS Code as my editor / debugger worked really well for all the languages here, giving me syntax highlighting, debugger stepping / variables viewing etc. Der InputStreamReaderand BufferedReaderconstructs are similar to (and I assume were copied by) Go.


C / C++

This was a trip down memory lane, as I wrote a lot of C code in the 1990s, some still running deep in telecoms networks somewhere. As the Geschichte von C predates the modern Web, it’s not surprising that library support is a manual task. We need to download (and compile) a recent version of Libcurl, linking to an OpenSSL library – see the README for actual steps.

Das fühlt sich im Vergleich zu modernen Sprachen wie eine Menge Arbeit an, vor allem wenn Go (oder Lua, oder Python, oder irgendeine andere Sprache) schnell genug für solche Aufgaben ist.

Die other thing I had forgotten, despite bearing the scars from previous battles, is the scariness of memory allocation! To keep the example simple, I preallocated the URL string length as 1024 characters, and bounds-checked the email address length (using strlen) before we concatenate into it (using strcat).

Wir behandeln den Autorisierungsstring mit einem verketteten API-Schlüssel auf die gleiche Weise ... auch wenn wir wissen, dass ein gültiger API-Schlüssel nie zu lang sein wird ... das ist kein Schutz! Benutzereingaben, die von einer Umgebungsvariablen kommen, können alles Mögliche sein. Sie müssen defensiv programmieren.

A more sophisticated developer might use mallocinstead of stack variable allocation, and calculate just how long the joined strings need to be. Having to think about this extra complexity gave me a Schmerzen in den Dioden auf der linken Seite; it reminded me of the risks that C programmers run every day, trying to avoid buffer overruns and unexpected side-effects. Which brings us to ..


Lua

Lua is known for its easy coexistence alongside a body of C code, and here at SparkPost, we Lua ausgiebig genutzt for Policy customisations inside our Momentum on-premises MTA. You can also use it as a stand-alone scripting language, and it’s pretty nice for that, too.

With Lua 5.3 and the luarocks package manager, we use libraries luasocket and luasec. Showing its C integration heritage, we link to our local OpenSSL library. The luarocks install process calls the gcc compiler (or whatever C compiler you are using), so adding new libraries takes a while.

The Lua code is quite simple. The characters — mark comments.  The function https.anfrage provides mehrere Rückgabewerte (a bit like Python and Go). String concatenation is done with the Betreiber  .. (instead of + in Python).

The response body from this call is handled with the “ltn12” module – see here. That enables efficient handling of data that could be returned in multiple “chunks”. As that article explains:

Die Tabellenfabrik erstellt eine Senke, die alle erhaltenen Daten in einer Tabelle speichert. Die Daten können später mit der Bibliotheksfunktion table.concat effizient zu einem einzigen String verkettet werden.

In unserem Beispiel wird lediglich die Tabelle t verkettet und ausgedruckt; Sie könnten einen Filter verwenden, um weitere Verarbeitungsschritte durchzuführen.


Perl

While Perl is famous for its Einzeiler, this is not one of them.  Perl was designed for very fast document search and modification, but is actually capable of so much more.  I once wrote an entire Inventory control suite in Perl.  Go figure.   A n y w a y…

This script makes use of LWP::UserAgent and HTTP::Request and optionally the JSON and Data::Dumper packages depending on how you want to see the output. As with all the other scripts on this page, you should pre-set an environment variable SPARKPOST_API_SCHLÜSSELto your generated API key that includes the Recipient Validation function. This script hard codes $recipient = ‘test@gmail.com’ but you can easily add command-line input or consume from a file.

After all the variables are populated, we load an HTTP:Request with GET parameters and send it to the LWP:UserAgent.  The resulting “message” is the result of the email validation test as an array.  You can use JSON and DUMPER to display the result or just pass the array on for additional processing.


VB.net

Visual Basic is not visual and it is not basic (IMHO), but it is #6 on the TIOBE-Sprachindex so here we go.

There are other ways to do this, but the easiest path to success is to use the Visual Studio SDK in a Windows platform. Fire up Visual Studio, start a new project and select Visual Basic, then select console.app.  Be sure to use the VB version not the C# version – it is easy to miss that in the SDK.


At this point you can edit lines manually or copy/paste the code von hier into VS and save a bunch of time. In order to make this code work, you need to add a Windows environment variable.  The easiest way to do this is to open a command prompt and use setx.exe like this: 

C:\Users\me>setx SPARKPOST_API_SCHLÜSSEL  "142<redacted<redacted>c531c3"

In Windows 10 wird dies auf Ihre Benutzerumgebung angewendet, ist aber nicht sofort in der aktuellen Befehlssitzung verfügbar, so dass das Testen mit einem "Set" nicht funktioniert, aber es wird für den Code verfügbar sein. Wenn Sie den im Repo enthaltenen Code erstellen und ausführen, sehen Sie das Validierungsergebnis.


Rost

Rust is a language for systems and web-services programming that is focused on performance, safety and concurrency. As Wikipedia says, Rust has been the “most loved programming language” in the Stack Overflow Developer Survey since 2016.

The Rust code in unserem Github-Repository uses the reqwest library with tokio async, similar to this example from the Rust cookbook. (That’s not a typo, the reqwest library name is spelled like that). We’ve included a cargo package manager Konfigurationsdatei, so you can build and run with:

cd rust_recipient_validation cargo run

Dadurch wird das Paket in ausführbaren Code kompiliert und ausgeführt:

Beendet dev [unoptimiert + debuginfo] target(s) in 0.10s Ausführung von `target/debug/rust_recipient_validation` Status: 200 OK Body: : (etc)

The code uses std:envto read the SPARKPOST_API_KEY environment variable. A match clause handles the case where the key is undefined. If all is well, a new reqwest::Kunde is created and an async call issued, followed by an .abwarten? (see here). Async, rather than the simpler blocking call, seems to be needed to set request headers. Response body text is read with a second .abwarten?, as per dieses Beispiel.


Summary

In diesem Artikel haben wir Code-Beispiele für die Empfängervalidierung in vielen Sprachen durchgespielt. Hier ist unsere Bitte an Sie.

Let us know if you think we missed your favorite language. We may not have as many examples as Das Fibonacci-Projekt, but we’d love to add some more. Also, if you think our examples can be improved, let us know!

Your new standard in Marketing, Pay & Sales. It's Bird

The right message -> to the right person -> am right time.

Your new standard in Marketing, Pay & Sales. It's Bird

The right message -> to the right person -> am right time.