Rust

Messaging

Email, SMS, push and chat messages sent through provider adapters (SMTP, SES, Mailgun, Sendgrid, Resend; Twilio, Vonage, Bird, WhatsApp and a dozen more SMS gateways with routing by calling code; FCM and APNs; Discord), with per-recipient results and send telemetry.
Rust 7,951 lines (5,896 code)split
PartCodeCommentsBlankTotalFiles
Rust source5,8961,4046517,95125
Rust tests5403571

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-messaging = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Messaging, each a complete program you can copy and run.

Getting started

utopia-messaging sends email, text messages, push notifications and Discord messages through the provider an application configured: SMTP or an email API, one of a dozen SMS gateways, APNs or FCM. A message is checked when it is built, a send reports a result per recipient, and only input no provider could deliver is an error.

Build an email

Every address is checked when the email is built, as are display names and extra headers. A recipient is a bare address or an entry with a display name.

Rust
use utopia_messaging::{Email, Reason, Recipient};

let email = Email::builder(
    [Recipient::named("john@example.test", "John Doe"), Recipient::from("jane@example.test")],
    "Your order has shipped",
    "It is on its way.",
    "Acme",
    "orders@example.test",
)
.header("List-Unsubscribe", "<https://example.test/u?token=abc>")
.build()?;
assert_eq!(email.to().len(), 2);
assert_eq!(email.reply_to_email(), "orders@example.test");

let refused = Email::builder(["john@c.c"], "Hi", "Body", "Acme", "orders@example.test").build().unwrap_err();
assert!(matches!(refused, utopia_messaging::Error::Invalid { reason: Reason::RecipientDomainInvalid, .. }));

Send a text message

An adapter sends one kind of message through one provider. The response says how many recipients were reached, and why each of the others was not.

Rust
use utopia_messaging::sms::Twilio;
use utopia_messaging::{Adapter, Message, Sms};

let twilio = Twilio::new("AC123", "auth-token").with_from(Some("+15550000000".into()));
let sent = twilio.send(&Message::from(Sms::new(["+15551234567"], "Your code is 123456"))).await?;
let response = sent.response().expect("one adapter, one response");
for result in response.details() {
    println!("{}: {} {}", result.recipient, result.status.as_str(), result.error);
}
Compiles in CI; needs a running service to execute.

Route text messages by country

GeoSms sends each recipient through the adapter registered for its calling code, the others through the default adapter, and reports each adapter's response by name.

Rust
use std::sync::Arc;

use utopia_messaging::sms::{GeoSms, Msg91, Twilio, calling_code};
use utopia_messaging::{Adapter, Message, Sms};

let router = GeoSms::new(Arc::new(Twilio::new("AC123", "auth-token")))
    .with_local(calling_code::INDIA, Arc::new(Msg91::new("SENDER", "auth-key", "template-id")));
assert_eq!(calling_code::from_phone_number("+91 98765 43210"), Some("91"));
let sent = router.send(&Message::from(Sms::new(["+919876543210", "+15551234567"], "123456"))).await?;
Compiles in CI; needs a running service to execute.

Send email through SMTP

The SMTP adapter tries each host of the list in order, and every recipient gets the server's own answer: one refused address does not fail the others, and a 5xx refusal is marked permanent.

Rust
use utopia_messaging::email::Smtp;
use utopia_messaging::{Adapter, Email, Message};

let smtp = Smtp::new("tls://smtp1.example.test:587;smtp2.example.test", 25)
    .with_credentials("user", "secret")
    .with_keep_alive(true);
let email = Email::builder(["john@example.test"], "Hello", "Body", "Acme", "noreply@example.test").build()?;
let sent = smtp.send(&Message::from(email)).await?;
for result in sent.response().map(|r| r.details()).unwrap_or_default() {
    if result.permanent {
        println!("do not retry {}: {}", result.recipient, result.error);
    }
}
smtp.disconnect().await;
Compiles in CI; needs a running service to execute.

Send a push notification

APNs and FCM sign their own tokens from the credentials given; every device token gets a result, and one the provider no longer knows reads Expired device token.

Rust
use utopia_messaging::push::Fcm;
use utopia_messaging::{Adapter, Message, Priority, Push};

let fcm = Fcm::new(service_account_json);
let push = Push::builder(["device-token"]).title("Hello").body("You have a new message").priority(Priority::High).build()?;
let sent = fcm.send(&Message::from(push)).await?;
Compiles in CI; needs a running service to execute.

Count sends with telemetry

Every send records how many recipients were reached and how many were not on the messaging.send counter, by provider, type and the message's origin.

Rust
use utopia_messaging::Configure;
use utopia_messaging::sms::Twilio;
use utopia_telemetry::MemoryTelemetry;

let telemetry = MemoryTelemetry::default();
let twilio = Twilio::new("AC123", "auth-token").with_telemetry(&telemetry);

Reference#

Email, SMS, push and chat messages, sent through provider adapters.

A message (Email, Sms, Push, Discord) is validated when built. An Adapter sends one kind of message through one provider: Adapter::send checks the message type and the recipient limit, processes it, and records how many recipients were reached on the messaging.send counter of the adapter's telemetry. A provider's answer, refusals included, comes back as a Response with a result per recipient; only input no provider can deliver is an Error.

Rust
use utopia_messaging::sms::Twilio;
use utopia_messaging::{Adapter, Message, Sms};

let twilio = Twilio::new("AC123", "auth-token").with_from(Some("+15550000000".into()));
let message = Message::from(Sms::new(["+15551234567"], "Your code is 123456"));
let sent = twilio.send(&message).await?;
let response = sent.response().expect("one adapter, one response");
println!("delivered to {}", response.delivered_to());
Compiles in CI; needs a running service to execute.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

adapterinternal
The `Adapter` trait every provider implements, and what they share: the checks and telemetry around a send (`Adapter::send`) and the `Base` that holds the requester and the send counter.
chat2 items
Chat adapters: `DiscordWebhook`.
email::mailguninternal
Undocumented.
email::mime4 items
An email as a MIME message on the wire, which the SMTP adapter hands over whole and SES sends as a raw message per recipient.
email3 items
Email adapters: `Smtp` (and `Mock`, SMTP to a catcher), `Ses`, `Mailgun`, `Sendgrid` and `Resend`, with `mime`, the MIME message SMTP and SES send.
email::resendinternal
Undocumented.
email::sendgridinternal
Undocumented.
email::sesinternal
Undocumented.
email::smtpinternal
Undocumented.
errorinternal
Undocumented.
httpinternal
How adapters reach provider APIs: a `Call` (or a `Multi` of concurrent calls) goes to a `Requester`, which answers with a `Reply`.
http2internal
The HTTP/2 transport APNs requires: TLS with ALPN `h2` (cleartext HTTP/2 with prior knowledge for `http://` URLs), one connection kept and shared by the requests sent through it.
jwt1 items
JSON Web Tokens as the push adapters sign them: ES256 for APNs, RS256 for FCM's OAuth2 assertion.
messageinternal
The messages adapters send: `Email`, `Sms`, `Push` and `Discord`.
message::classinternal
Undocumented.
push6 items
Push adapters: `Apns` (Apple, HTTP/2 with an ES256 token) and `Fcm` (Firebase, with an RS256 service-account assertion exchanged for an OAuth2 access token).
responseinternal
What a send reports: how many recipients it reached, and a result per recipient.
sms::birdinternal
Undocumented.
sms::calling_code189 items
Country calling codes, and the one a phone number starts with.
sms::fast2smsinternal
Undocumented.
sms::gatewaysinternal
The SMS gateways with one request per send and a plain answer.
sms::geosmsinternal
Undocumented.
sms1 items
SMS adapters: a dozen gateways, `WhatsApp` one-time passcodes, `Mock` for a local request catcher, and `GeoSms`, which routes each recipient to an adapter by calling code (`calling_code`).
sms::whatsappinternal
Undocumented.
valuesinternal
Undocumented.

API#

What utopia_messaging exports at its root.