Usage | laravel-mailcoach-sdk-rust | Spatie       

 SPATIE  

laravel-mailcoach-sdk-rust
==========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-mailcoach-sdk-rust](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-mailcoach-sdk-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Add a subscriber ](#content-add-a-subscriber)
2. [ Read all campaign pages ](#content-read-all-campaign-pages)
3. [ Create a newsletter draft ](#content-create-a-newsletter-draft)
4. [ Manage resources ](#content-manage-resources)
5. [ Send a transactional template ](#content-send-a-transactional-template)
6. [ Custom endpoints ](#content-custom-endpoints)
7. [ Handle failures ](#content-handle-failures)

Add a subscriber
--------------------------------------------------------------------------------------------------------

```
let subscriber = client
    .create_subscriber("list-uuid", &CreateSubscriber::new("reader@example.com"))
    .await?;

println!("{}", subscriber.uuid);
```

`CreateSubscriber` also accepts names, tags, custom attributes, `strict`, and `skip_confirmation`. Unset options are omitted. The SDK does not bypass double opt-in by default.

`find_by_email(list_uuid, email)` returns `None` only for an empty successful result. It preserves plus signs and other query characters. Authentication, validation and connection failures remain errors. `subscriber(uuid)` retrieves a record directly. `subscribers(list_uuid, options)` returns a page.

`unsubscribe_subscriber`, `resubscribe_subscriber`, `add_subscriber_tags`, and `remove_subscriber_tags` each send one request and accept empty successful responses. They never create a missing subscriber implicitly. Tag addition preserves existing tags; removal affects only the supplied tags. The caller must decide when resubscription is appropriate.

Read all campaign pages
-----------------------------------------------------------------------------------------------------------------------------

```
let options = ListOptions::default().sort("-sent").filter("status", "sent");
let mut page = client.campaigns(&options).await?;

loop {
    for campaign in &page.data {
        let details = client.campaign(&campaign.uuid).await?;
        println!("{}", details.webview_html.as_deref().unwrap_or(""));
    }
    let Some(next) = client.next_page(&page).await? else { break };
    page = next;
}
```

`ListOptions` accepts `page`, `per_page`, `sort`, and server filter names. Filters use the `filter[name]` convention and are URL-encoded once. Allowed filters and sorts depend on the endpoint and Mailcoach version. Unset values use server defaults.

```
use spatie_mailcoach_sdk::ListOptions;

let options = ListOptions::default()
    .page(2)
    .per_page(25)
    .sort("-sent")
    .filter("status", "sent");
```

`Page` exposes `data`, `links`, and `meta`. `next_page` and `previous_page` follow the server's absolute, root-relative, or API-base-relative navigation URL, preserving its query parameters. A missing link returns `None`. Links outside the configured origin or API path fail before credentials are sent. Fix a self-hosted installation's public URL configuration if it returns links on a different origin.

Campaign status is a string so new statuses remain readable. Timestamps remain server strings rather than imposing a date format on different installations. Nullable HTML and timestamp fields use `Option<String>`. Additional resource fields are retained in `extra`.

Create a newsletter draft
-----------------------------------------------------------------------------------------------------------------------------------

```
let draft = CreateCampaign {
    subject: Some("Newsletter #13".into()),
    from_email: Some("writer@example.com".into()),
    from_name: Some("Writer".into()),
    template_uuid: Some("template-uuid".into()),
    fields: [
        ("title".into(), serde_json::json!("Newsletter #13")),
        ("content".into(), serde_json::json!("# News\n\nHello from Rust.")),
    ].into(),
    ..CreateCampaign::new("Newsletter #13", "list-uuid")
};
let campaign = client.create_campaign(&draft).await?;
```

Use `html` instead of template fields when supplying HTML directly. The installation validates template fields and sender settings. Creating a campaign does not send or schedule it. Call `send_test(uuid, &["reader@example.com"])` for a test or `send(uuid)` to send deliberately.

Manage resources
--------------------------------------------------------------------------------------------------------

All create and update methods accept serializable application structs or JSON objects. Partial updates send exactly the supplied attributes. Subscribers use PATCH; other resource updates use PUT.

- Lists: `email_lists(options)`, `email_list(uuid)`, `create_email_list(attributes)`, `update_email_list(uuid, attributes)`, `delete_email_list(uuid)`.
- List tags: `add_tag_to_email_list(list, attributes)`, `update_tag_on_email_list(list, tag, attributes)`, `delete_tag_from_email_list(list, tag)`.
- Subscribers: `update_subscriber(uuid, attributes)`, `delete_subscriber(uuid)`, `confirm_subscriber(uuid)`, `resend_confirmation(uuid)` supplement the methods above. `unsubscribe_email(list, email)` unsubscribes by address. `Subscriber::is_unconfirmed()` checks pending confirmation.
- Campaigns: `update_campaign(uuid, attributes)`, `delete_campaign(uuid)`, `send_test(uuid, emails)`, `send(uuid)`. Test recipient slices are sent as one comma-separated string.
- Reports: `campaign_opens`, `campaign_clicks`, `campaign_bounces`, and `campaign_unsubscribes` take a campaign UUID and list options and return typed pages.
- Templates: `templates(options)`, `template(uuid)`, `create_template(attributes)`, `update_template(uuid, attributes)`, `delete_template(uuid)`.
- Automation mail: `automation_mails(options)`, `automation_mail(uuid)`, `create_automation_mail(attributes)`, `update_automation_mail(uuid, attributes)`, `delete_automation_mail(uuid)`. `trigger_automation(uuid, subscriber_uuids)` triggers an automation for the selected subscribers.
- Transactional mail: `transactional_mails(options)`, `transactional_mail(uuid)`, `transactional_mail_templates(options)`, `transactional_mail_template(uuid)`.

Returned values are serializable data, not active records. To save changed resource fields, pass them to the appropriate client update method. Unknown fields round-trip through `extra`. Use explicit request objects to avoid sending read-only server fields.

Send a transactional template
-----------------------------------------------------------------------------------------------------------------------------------------------

```
client.send_transaction_mail(&serde_json::json!({
    "mail_name": "receipt",
    "from": "sender@example.com",
    "to": "reader@example.com",
    "replacements": {"name": "Reader"},
    "attachments": [{
        "name": "receipt.txt", "content": "aGVsbG8=",
        "content_type": "text/plain", "content_id": null
    }],
    "store": false
})).await?;
```

Optional fields include `subject`, `cc`, `bcc`, `reply_to`, and `fake`. Supply attachment content as base64. A `false` option is sent unchanged, not omitted. The SDK does not queue messages locally or retry sends.

Custom endpoints
--------------------------------------------------------------------------------------------------------

`get(uri)`, `post(uri, payload)`, `put(uri, payload)`, `patch(uri, payload)`, and `delete(uri, optional_payload)` expose endpoints not covered by a typed method. `request(Method, uri, optional_payload)` accepts a method directly. Use API-relative URIs such as `templates?filter[name]=receipt`. Absolute URIs must remain inside the configured API origin and path, even for writes.

These methods return JSON values, or strings for non-JSON and empty success bodies. Typed resource methods still reject malformed JSON. All methods share authentication, timeouts, error classification, and the no-retry policy.

Handle failures
-----------------------------------------------------------------------------------------------------

```
match client.campaign("campaign-uuid").await {
    Ok(campaign) => println!("{}", campaign.name),
    Err(Error::Api(error)) if error.kind == ApiErrorKind::NotFound => {
        println!("Campaign no longer exists");
    }
    Err(error) => return Err(error),
}
```

API errors retain their status, classification, message, field validation errors, original body bytes and optional `Retry-After`. The header can contain seconds or an HTTP date. Error display includes only the status; debug output includes the body and may expose personal data.

Connection and timeout failures use `Error::Transport`. Invalid successful JSON uses `Error::Decode`, rather than silently returning empty records. The SDK does not retry requests or follow redirects. If a write times out, its server-side outcome may be unknown. Do not retry a subscriber or draft creation blindly.

- Requests have a 30-second total timeout. Use `Mailcoach::with_timeout(token, endpoint, duration)` to change it. Zero is rejected at construction.
- Match `Error::Config(ConfigError::MissingToken | ConfigError::InvalidToken | ConfigError::InvalidEndpoint | ConfigError::InvalidTimeout)` to handle configuration failures without parsing text.
- Match `Error::InvalidIdentifier` for invalid resource identifiers and `Error::InvalidApiUrl` for unsafe links.
- Cloning a client shares its connection pool.

The HTTP examples compile but do not execute in doctests. The integration suite executes these workflows against synthetic local HTTP responses, never a production account.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
