missive 0.6.2

Compose, deliver, preview, and test emails in Rust - pluggable providers with zero configuration code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! # Missive
//!
//! Compose, deliver, and test emails in Rust. Plug and play.
//!
//! ## Quick Start
//!
//! Set environment variables:
//! ```bash
//! EMAIL_PROVIDER=resend
//! RESEND_API_KEY=re_xxxxx
//! EMAIL_FROM=noreply@example.com
//! EMAIL_FROM_NAME=My App
//! ```
//!
//! Send emails from anywhere:
//! ```rust,ignore
//! use missive::{Email, deliver};
//!
//! let email = Email::new()
//!     .to("user@example.com")
//!     .subject("Welcome!")
//!     .text_body("Hello");
//!
//! deliver(&email).await?;
//! ```
//!
//! That's it. No configuration code needed.
//!
//! ## Per-Call Mailer Override
//!
//! ```rust,ignore
//! use missive::{Email, deliver_with};
//! use missive::providers::ResendMailer;
//!
//! let mailer = ResendMailer::new("different_api_key");
//! deliver_with(&email, &mailer).await?;
//! ```
//!
//! ## Environment Variables
//!
//! | Variable | Description |
//! |----------|-------------|
//! | `EMAIL_PROVIDER` | `smtp`, `resend`, `unsent`, `postmark`, `sendgrid`, `brevo`, `mailgun`, `amazon_ses`, `mailtrap`, `socketlabs`, `gmail`, `protonbridge`, `jmap`, `logger`, `logger_full` |
//! | `EMAIL_FROM` | Default sender email |
//! | `EMAIL_FROM_NAME` | Default sender name |
//! | `SMTP_HOST` | SMTP server host |
//! | `SMTP_PORT` | SMTP server port (default: 587) |
//! | `SMTP_USERNAME` | SMTP username |
//! | `SMTP_PASSWORD` | SMTP password |
//! | `RESEND_API_KEY` | Resend API key |
//! | `UNSENT_API_KEY` | Unsent API key |
//! | `POSTMARK_API_KEY` | Postmark API key |
//! | `SENDGRID_API_KEY` | SendGrid API key |
//! | `BREVO_API_KEY` | Brevo API key |
//! | `MAILGUN_API_KEY` | Mailgun API key |
//! | `MAILGUN_DOMAIN` | Mailgun sending domain |
//! | `AWS_REGION` | AWS region for SES |
//! | `AWS_ACCESS_KEY_ID` | AWS access key |
//! | `AWS_SECRET_ACCESS_KEY` | AWS secret key |
//! | `MAILTRAP_API_KEY` | Mailtrap API key |
//! | `MAILTRAP_SANDBOX_INBOX_ID` | Mailtrap sandbox inbox ID (optional) |
//! | `SOCKETLABS_SERVER_ID` | SocketLabs server ID |
//! | `SOCKETLABS_API_KEY` | SocketLabs API key |
//! | `GMAIL_ACCESS_TOKEN` | Gmail OAuth2 access token |
//! | `PROTONBRIDGE_USERNAME` | Proton Bridge SMTP username |
//! | `PROTONBRIDGE_PASSWORD` | Proton Bridge SMTP password |
//! | `PROTONBRIDGE_HOST` | Proton Bridge host (default: 127.0.0.1) |
//! | `PROTONBRIDGE_PORT` | Proton Bridge port (default: 1025) |
//! | `JMAP_URL` | JMAP server URL |
//! | `JMAP_USERNAME` | JMAP username (for basic auth) |
//! | `JMAP_PASSWORD` | JMAP password (for basic auth) |
//! | `JMAP_BEARER_TOKEN` | JMAP bearer token (for OAuth2) |
//!
//! ## Feature Flags
//!
//! - `smtp` - SMTP provider via lettre
//! - `resend` - Resend API provider
//! - `unsent` - Unsent API provider
//! - `postmark` - Postmark API provider
//! - `sendgrid` - SendGrid API provider
//! - `brevo` - Brevo API provider (formerly Sendinblue)
//! - `mailgun` - Mailgun API provider
//! - `amazon_ses` - Amazon SES API provider
//! - `mailtrap` - Mailtrap API provider (testing/staging)
//! - `socketlabs` - SocketLabs Injection API provider
//! - `gmail` - Gmail API provider (OAuth2)
//! - `protonbridge` - Proton Bridge provider (local SMTP)
//! - `jmap` - JMAP protocol provider (Stalwart, Fastmail, etc.)
//! - `local` - LocalMailer for development and testing
//! - `preview` - Mailbox preview web UI
//! - `metrics` - Prometheus-style metrics (counters/histograms)
//! - `dev` - Enables local and preview
//!
//! ## Metrics
//!
//! Enable `features = ["metrics"]` to emit Prometheus-style metrics:
//!
//! | Metric | Type | Labels | Description |
//! |--------|------|--------|-------------|
//! | `missive_emails_total` | Counter | provider, status | Total emails sent |
//! | `missive_delivery_duration_seconds` | Histogram | provider | Delivery duration |
//! | `missive_batch_total` | Counter | provider, status | Total batch operations |
//! | `missive_batch_size` | Histogram | provider | Emails per batch |
//!
//! Install a recorder (e.g., `metrics-exporter-prometheus`) in your app to collect them.

/// The version of the missive crate.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

mod address;
mod attachment;
mod email;
mod error;
pub mod interceptor;
mod mailer;

pub mod providers;

#[cfg(feature = "local")]
mod storage;

#[cfg(feature = "local")]
pub mod testing;

#[cfg(any(
    feature = "preview",
    feature = "preview-axum",
    feature = "preview-actix"
))]
pub mod preview;

#[cfg(feature = "templates")]
mod template;
#[cfg(feature = "templates")]
pub use template::{EmailTemplate, EmailTemplateExt};

use parking_lot::RwLock;
use std::env;
use std::sync::Arc;

#[cfg(feature = "metrics")]
use std::time::Instant;

// Re-exports
pub use address::{Address, ToAddress};
pub use attachment::{Attachment, AttachmentType};
pub use email::Email;
pub use error::MailError;
pub use interceptor::{Interceptor, InterceptorExt, WithInterceptor};
pub use mailer::{DeliveryResult, Mailer, MailerExt};

#[cfg(feature = "local")]
pub use storage::{MemoryStorage, Storage, StoredEmail};

// ============================================================================
// Global Mailer Configuration
// ============================================================================

/// Global mailer - swappable for testing
static MAILER: RwLock<Option<Arc<dyn Mailer>>> = RwLock::new(None);

/// Global shared storage for LocalMailer (used by preview UI).
#[cfg(feature = "local")]
static LOCAL_STORAGE: std::sync::OnceLock<Arc<MemoryStorage>> = std::sync::OnceLock::new();

/// Get the shared storage for the LocalMailer.
///
/// Use this to mount the preview UI when using `EMAIL_PROVIDER=local`.
///
/// ```rust,ignore
/// use missive::local_storage;
/// use missive::preview::mailbox_router;
///
/// if let Some(storage) = local_storage() {
///     app = app.nest("/dev/mailbox", mailbox_router(storage));
/// }
/// ```
#[cfg(feature = "local")]
pub fn local_storage() -> Option<Arc<MemoryStorage>> {
    LOCAL_STORAGE.get().cloned()
}

/// Get the default from address from environment.
pub fn default_from() -> Option<Address> {
    let email = env::var("EMAIL_FROM").ok()?;
    match env::var("EMAIL_FROM_NAME").ok() {
        Some(name) => Some(Address::with_name(name, email)),
        None => Some(Address::new(email)),
    }
}

/// Auto-detect provider based on enabled features and available API keys.
fn detect_provider() -> Option<&'static str> {
    // Check API keys first (explicit configuration)
    #[cfg(feature = "resend")]
    if env::var("RESEND_API_KEY").is_ok() {
        return Some("resend");
    }
    #[cfg(feature = "sendgrid")]
    if env::var("SENDGRID_API_KEY").is_ok() {
        return Some("sendgrid");
    }
    #[cfg(feature = "postmark")]
    if env::var("POSTMARK_API_KEY").is_ok() {
        return Some("postmark");
    }
    #[cfg(feature = "unsent")]
    if env::var("UNSENT_API_KEY").is_ok() {
        return Some("unsent");
    }
    #[cfg(feature = "brevo")]
    if env::var("BREVO_API_KEY").is_ok() {
        return Some("brevo");
    }
    #[cfg(feature = "mailgun")]
    if env::var("MAILGUN_API_KEY").is_ok() && env::var("MAILGUN_DOMAIN").is_ok() {
        return Some("mailgun");
    }
    #[cfg(feature = "amazon_ses")]
    if env::var("AWS_ACCESS_KEY_ID").is_ok()
        && env::var("AWS_SECRET_ACCESS_KEY").is_ok()
        && env::var("AWS_REGION").is_ok()
    {
        return Some("amazon_ses");
    }
    #[cfg(feature = "mailtrap")]
    if env::var("MAILTRAP_API_KEY").is_ok() {
        return Some("mailtrap");
    }
    #[cfg(feature = "socketlabs")]
    if env::var("SOCKETLABS_API_KEY").is_ok() && env::var("SOCKETLABS_SERVER_ID").is_ok() {
        return Some("socketlabs");
    }
    #[cfg(feature = "gmail")]
    if env::var("GMAIL_ACCESS_TOKEN").is_ok() {
        return Some("gmail");
    }
    #[cfg(feature = "protonbridge")]
    if env::var("PROTONBRIDGE_USERNAME").is_ok() && env::var("PROTONBRIDGE_PASSWORD").is_ok() {
        return Some("protonbridge");
    }
    #[cfg(feature = "jmap")]
    if env::var("JMAP_URL").is_ok()
        && (env::var("JMAP_BEARER_TOKEN").is_ok()
            || (env::var("JMAP_USERNAME").is_ok() && env::var("JMAP_PASSWORD").is_ok()))
    {
        return Some("jmap");
    }
    #[cfg(feature = "smtp")]
    if env::var("SMTP_HOST").is_ok() {
        return Some("smtp");
    }
    #[cfg(feature = "local")]
    {
        return Some("local");
    }
    #[allow(unreachable_code)]
    None
}

/// Create mailer from environment variables.
fn create_mailer_from_env() -> Result<Arc<dyn Mailer>, MailError> {
    let provider = match env::var("EMAIL_PROVIDER") {
        Ok(p) => p.to_lowercase(),
        Err(_) => {
            // Auto-detect based on features and API keys
            match detect_provider() {
                Some(p) => {
                    tracing::debug!(provider = p, "Auto-detected email provider");
                    p.to_string()
                }
                None => {
                    return Err(MailError::Configuration(
                        "EMAIL_PROVIDER not set and could not auto-detect. \
                        Set EMAIL_PROVIDER or ensure an API key is configured."
                            .into(),
                    ));
                }
            }
        }
    };

    match provider.as_str() {
        #[cfg(feature = "smtp")]
        "smtp" => {
            let host = env::var("SMTP_HOST")
                .map_err(|_| MailError::Configuration("SMTP_HOST not set".into()))?;
            let port: u16 = env::var("SMTP_PORT")
                .unwrap_or_else(|_| "587".to_string())
                .parse()
                .unwrap_or(587);
            let username = env::var("SMTP_USERNAME").unwrap_or_default();
            let password = env::var("SMTP_PASSWORD").unwrap_or_default();

            let mailer = if username.is_empty() {
                providers::SmtpMailer::new(&host, port).build()
            } else {
                providers::SmtpMailer::new(&host, port)
                    .credentials(&username, &password)
                    .build()
            };
            Ok(Arc::new(mailer))
        }
        #[cfg(not(feature = "smtp"))]
        "smtp" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=smtp but 'smtp' feature is not enabled. \
            Add `features = [\"smtp\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "resend")]
        "resend" => {
            let key = env::var("RESEND_API_KEY")
                .map_err(|_| MailError::Configuration("RESEND_API_KEY not set".into()))?;
            Ok(Arc::new(providers::ResendMailer::new(&key)))
        }
        #[cfg(not(feature = "resend"))]
        "resend" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=resend but 'resend' feature is not enabled. \
            Add `features = [\"resend\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "unsent")]
        "unsent" => {
            let key = env::var("UNSENT_API_KEY")
                .map_err(|_| MailError::Configuration("UNSENT_API_KEY not set".into()))?;
            Ok(Arc::new(providers::UnsentMailer::new(&key)))
        }
        #[cfg(not(feature = "unsent"))]
        "unsent" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=unsent but 'unsent' feature is not enabled. \
            Add `features = [\"unsent\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "postmark")]
        "postmark" => {
            let key = env::var("POSTMARK_API_KEY")
                .map_err(|_| MailError::Configuration("POSTMARK_API_KEY not set".into()))?;
            Ok(Arc::new(providers::PostmarkMailer::new(&key)))
        }
        #[cfg(not(feature = "postmark"))]
        "postmark" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=postmark but 'postmark' feature is not enabled. \
            Add `features = [\"postmark\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "sendgrid")]
        "sendgrid" => {
            let key = env::var("SENDGRID_API_KEY")
                .map_err(|_| MailError::Configuration("SENDGRID_API_KEY not set".into()))?;
            Ok(Arc::new(providers::SendGridMailer::new(&key)))
        }
        #[cfg(not(feature = "sendgrid"))]
        "sendgrid" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=sendgrid but 'sendgrid' feature is not enabled. \
            Add `features = [\"sendgrid\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "brevo")]
        "brevo" => {
            let key = env::var("BREVO_API_KEY")
                .map_err(|_| MailError::Configuration("BREVO_API_KEY not set".into()))?;
            Ok(Arc::new(providers::BrevoMailer::new(&key)))
        }
        #[cfg(not(feature = "brevo"))]
        "brevo" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=brevo but 'brevo' feature is not enabled. \
            Add `features = [\"brevo\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "mailgun")]
        "mailgun" => {
            let key = env::var("MAILGUN_API_KEY")
                .map_err(|_| MailError::Configuration("MAILGUN_API_KEY not set".into()))?;
            let domain = env::var("MAILGUN_DOMAIN")
                .map_err(|_| MailError::Configuration("MAILGUN_DOMAIN not set".into()))?;
            let mut mailer = providers::MailgunMailer::new(&key, &domain);
            // Check for EU endpoint
            if let Ok(base_url) = env::var("MAILGUN_BASE_URL") {
                mailer = mailer.base_url(base_url);
            }
            Ok(Arc::new(mailer))
        }
        #[cfg(not(feature = "mailgun"))]
        "mailgun" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=mailgun but 'mailgun' feature is not enabled. \
            Add `features = [\"mailgun\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "amazon_ses")]
        "amazon_ses" => {
            let region = env::var("AWS_REGION")
                .map_err(|_| MailError::Configuration("AWS_REGION not set".into()))?;
            let access_key = env::var("AWS_ACCESS_KEY_ID")
                .map_err(|_| MailError::Configuration("AWS_ACCESS_KEY_ID not set".into()))?;
            let secret = env::var("AWS_SECRET_ACCESS_KEY")
                .map_err(|_| MailError::Configuration("AWS_SECRET_ACCESS_KEY not set".into()))?;
            Ok(Arc::new(providers::AmazonSesMailer::new(region, access_key, secret)))
        }
        #[cfg(not(feature = "amazon_ses"))]
        "amazon_ses" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=amazon_ses but 'amazon_ses' feature is not enabled. \
            Add `features = [\"amazon_ses\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "mailtrap")]
        "mailtrap" => {
            let key = env::var("MAILTRAP_API_KEY")
                .map_err(|_| MailError::Configuration("MAILTRAP_API_KEY not set".into()))?;
            let mut mailer = providers::MailtrapMailer::new(&key);
            // Check for sandbox mode
            if let Ok(inbox_id) = env::var("MAILTRAP_SANDBOX_INBOX_ID") {
                mailer = mailer.sandbox_inbox_id(inbox_id);
            }
            Ok(Arc::new(mailer))
        }
        #[cfg(not(feature = "mailtrap"))]
        "mailtrap" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=mailtrap but 'mailtrap' feature is not enabled. \
            Add `features = [\"mailtrap\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "socketlabs")]
        "socketlabs" => {
            let server_id = env::var("SOCKETLABS_SERVER_ID")
                .map_err(|_| MailError::Configuration("SOCKETLABS_SERVER_ID not set".into()))?;
            let api_key = env::var("SOCKETLABS_API_KEY")
                .map_err(|_| MailError::Configuration("SOCKETLABS_API_KEY not set".into()))?;
            Ok(Arc::new(providers::SocketLabsMailer::new(server_id, api_key)))
        }
        #[cfg(not(feature = "socketlabs"))]
        "socketlabs" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=socketlabs but 'socketlabs' feature is not enabled. \
            Add `features = [\"socketlabs\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "gmail")]
        "gmail" => {
            let token = env::var("GMAIL_ACCESS_TOKEN")
                .map_err(|_| MailError::Configuration("GMAIL_ACCESS_TOKEN not set".into()))?;
            Ok(Arc::new(providers::GmailMailer::new(token)))
        }
        #[cfg(not(feature = "gmail"))]
        "gmail" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=gmail but 'gmail' feature is not enabled. \
            Add `features = [\"gmail\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "protonbridge")]
        "protonbridge" => {
            let username = env::var("PROTONBRIDGE_USERNAME")
                .map_err(|_| MailError::Configuration("PROTONBRIDGE_USERNAME not set".into()))?;
            let password = env::var("PROTONBRIDGE_PASSWORD")
                .map_err(|_| MailError::Configuration("PROTONBRIDGE_PASSWORD not set".into()))?;
            let mut builder = providers::ProtonBridgeMailer::new(&username, &password);
            if let Ok(host) = env::var("PROTONBRIDGE_HOST") {
                builder = builder.host(&host);
            }
            if let Ok(port) = env::var("PROTONBRIDGE_PORT") {
                if let Ok(port) = port.parse() {
                    builder = builder.port(port);
                }
            }
            Ok(Arc::new(builder.build()))
        }
        #[cfg(not(feature = "protonbridge"))]
        "protonbridge" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=protonbridge but 'protonbridge' feature is not enabled. \
            Add `features = [\"protonbridge\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "jmap")]
        "jmap" => {
            let url = env::var("JMAP_URL")
                .map_err(|_| MailError::Configuration("JMAP_URL not set".into()))?;
            let builder = providers::JmapMailer::new(&url);
            let mailer = if let Ok(token) = env::var("JMAP_BEARER_TOKEN") {
                builder.bearer_token(&token).build()
            } else {
                let username = env::var("JMAP_USERNAME")
                    .map_err(|_| MailError::Configuration("JMAP_USERNAME not set".into()))?;
                let password = env::var("JMAP_PASSWORD")
                    .map_err(|_| MailError::Configuration("JMAP_PASSWORD not set".into()))?;
                builder.credentials(&username, &password).build()
            };
            Ok(Arc::new(mailer))
        }
        #[cfg(not(feature = "jmap"))]
        "jmap" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=jmap but 'jmap' feature is not enabled. \
            Add `features = [\"jmap\"]` to Cargo.toml"
                .into(),
        )),

        #[cfg(feature = "local")]
        "local" => {
            // Use global shared storage so preview UI can access emails
            let storage = LOCAL_STORAGE.get_or_init(MemoryStorage::shared);
            Ok(Arc::new(providers::LocalMailer::with_storage(Arc::clone(storage))))
        }
        #[cfg(not(feature = "local"))]
        "local" => Err(MailError::Configuration(
            "EMAIL_PROVIDER=local but 'local' feature is not enabled. \
            Add `features = [\"local\"]` to Cargo.toml"
                .into(),
        )),

        "logger" => Ok(Arc::new(providers::LoggerMailer::new())),
        "logger_full" => Ok(Arc::new(providers::LoggerMailer::full())),

        _ => Err(MailError::Configuration(format!(
            "Unknown EMAIL_PROVIDER: {}. Valid providers are: smtp, resend, unsent, postmark, sendgrid, brevo, mailgun, amazon_ses, mailtrap, socketlabs, gmail, protonbridge, jmap, local, logger, logger_full",
            provider
        ))),
    }
}

/// Get or initialize the global mailer.
fn get_mailer() -> Result<Arc<dyn Mailer>, MailError> {
    // Fast path: already configured
    {
        let guard = MAILER.read();
        if let Some(ref mailer) = *guard {
            return Ok(Arc::clone(mailer));
        }
    }

    // Slow path: need to configure
    let mailer = create_mailer_from_env()?;
    let mut guard = MAILER.write();

    // Double-check after acquiring write lock
    if guard.is_none() {
        *guard = Some(Arc::clone(&mailer));
    }

    Ok(guard.as_ref().unwrap().clone())
}

/// Check if email is configured (env vars are set and feature is enabled).
///
/// Returns `true` only if both:
/// 1. The required environment variables for the provider are set
/// 2. The corresponding feature flag is enabled
///
/// Supports auto-detection: if `EMAIL_PROVIDER` is not set, checks for
/// available API keys and enabled features.
///
/// Logs a warning if the provider is specified but the feature flag is not enabled.
pub fn is_configured() -> bool {
    let provider = match env::var("EMAIL_PROVIDER") {
        Ok(p) => p,
        Err(_) => {
            // Auto-detect
            match detect_provider() {
                Some(p) => p.to_string(),
                None => return false,
            }
        }
    };
    match provider.to_lowercase().as_str() {
        #[cfg(feature = "smtp")]
        "smtp" => env::var("SMTP_HOST").is_ok(),
        #[cfg(not(feature = "smtp"))]
        "smtp" => {
            tracing::warn!(
                "EMAIL_PROVIDER=smtp but 'smtp' feature is not enabled. \
                Add `features = [\"smtp\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "resend")]
        "resend" => env::var("RESEND_API_KEY").is_ok(),
        #[cfg(not(feature = "resend"))]
        "resend" => {
            tracing::warn!(
                "EMAIL_PROVIDER=resend but 'resend' feature is not enabled. \
                Add `features = [\"resend\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "unsent")]
        "unsent" => env::var("UNSENT_API_KEY").is_ok(),
        #[cfg(not(feature = "unsent"))]
        "unsent" => {
            tracing::warn!(
                "EMAIL_PROVIDER=unsent but 'unsent' feature is not enabled. \
                Add `features = [\"unsent\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "postmark")]
        "postmark" => env::var("POSTMARK_API_KEY").is_ok(),
        #[cfg(not(feature = "postmark"))]
        "postmark" => {
            tracing::warn!(
                "EMAIL_PROVIDER=postmark but 'postmark' feature is not enabled. \
                Add `features = [\"postmark\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "sendgrid")]
        "sendgrid" => env::var("SENDGRID_API_KEY").is_ok(),
        #[cfg(not(feature = "sendgrid"))]
        "sendgrid" => {
            tracing::warn!(
                "EMAIL_PROVIDER=sendgrid but 'sendgrid' feature is not enabled. \
                Add `features = [\"sendgrid\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "brevo")]
        "brevo" => env::var("BREVO_API_KEY").is_ok(),
        #[cfg(not(feature = "brevo"))]
        "brevo" => {
            tracing::warn!(
                "EMAIL_PROVIDER=brevo but 'brevo' feature is not enabled. \
                Add `features = [\"brevo\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "mailgun")]
        "mailgun" => env::var("MAILGUN_API_KEY").is_ok() && env::var("MAILGUN_DOMAIN").is_ok(),
        #[cfg(not(feature = "mailgun"))]
        "mailgun" => {
            tracing::warn!(
                "EMAIL_PROVIDER=mailgun but 'mailgun' feature is not enabled. \
                Add `features = [\"mailgun\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "amazon_ses")]
        "amazon_ses" => {
            env::var("AWS_REGION").is_ok()
                && env::var("AWS_ACCESS_KEY_ID").is_ok()
                && env::var("AWS_SECRET_ACCESS_KEY").is_ok()
        }
        #[cfg(not(feature = "amazon_ses"))]
        "amazon_ses" => {
            tracing::warn!(
                "EMAIL_PROVIDER=amazon_ses but 'amazon_ses' feature is not enabled. \
                Add `features = [\"amazon_ses\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "mailtrap")]
        "mailtrap" => env::var("MAILTRAP_API_KEY").is_ok(),
        #[cfg(not(feature = "mailtrap"))]
        "mailtrap" => {
            tracing::warn!(
                "EMAIL_PROVIDER=mailtrap but 'mailtrap' feature is not enabled. \
                Add `features = [\"mailtrap\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "socketlabs")]
        "socketlabs" => {
            env::var("SOCKETLABS_SERVER_ID").is_ok() && env::var("SOCKETLABS_API_KEY").is_ok()
        }
        #[cfg(not(feature = "socketlabs"))]
        "socketlabs" => {
            tracing::warn!(
                "EMAIL_PROVIDER=socketlabs but 'socketlabs' feature is not enabled. \
                Add `features = [\"socketlabs\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "gmail")]
        "gmail" => env::var("GMAIL_ACCESS_TOKEN").is_ok(),
        #[cfg(not(feature = "gmail"))]
        "gmail" => {
            tracing::warn!(
                "EMAIL_PROVIDER=gmail but 'gmail' feature is not enabled. \
                Add `features = [\"gmail\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "protonbridge")]
        "protonbridge" => {
            env::var("PROTONBRIDGE_USERNAME").is_ok() && env::var("PROTONBRIDGE_PASSWORD").is_ok()
        }
        #[cfg(not(feature = "protonbridge"))]
        "protonbridge" => {
            tracing::warn!(
                "EMAIL_PROVIDER=protonbridge but 'protonbridge' feature is not enabled. \
                Add `features = [\"protonbridge\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "jmap")]
        "jmap" => {
            env::var("JMAP_URL").is_ok()
                && (env::var("JMAP_BEARER_TOKEN").is_ok()
                    || (env::var("JMAP_USERNAME").is_ok() && env::var("JMAP_PASSWORD").is_ok()))
        }
        #[cfg(not(feature = "jmap"))]
        "jmap" => {
            tracing::warn!(
                "EMAIL_PROVIDER=jmap but 'jmap' feature is not enabled. \
                Add `features = [\"jmap\"]` to Cargo.toml"
            );
            false
        }

        #[cfg(feature = "local")]
        "local" => true,
        #[cfg(not(feature = "local"))]
        "local" => {
            tracing::warn!(
                "EMAIL_PROVIDER=local but 'local' feature is not enabled. \
                Add `features = [\"local\"]` to Cargo.toml"
            );
            false
        }

        "logger" | "logger_full" => true,

        _ => false,
    }
}

/// Initialize the mailer from environment variables.
///
/// Call this at startup if you need early initialization (e.g., for preview UI).
/// Returns Ok if successful, Err if configuration is invalid.
///
/// ```rust,ignore
/// // In main.rs
/// missive::init().ok(); // Ignore error if email not configured
/// ```
pub fn init() -> Result<(), MailError> {
    if !is_configured() {
        return Err(MailError::NotConfigured);
    }
    let _ = get_mailer()?;
    Ok(())
}

/// Validate an email has required fields.
fn validate(email: &Email) -> Result<(), MailError> {
    if email.from.is_none() && default_from().is_none() {
        return Err(MailError::MissingField("from"));
    }
    if email.to.is_empty() {
        return Err(MailError::MissingField("to"));
    }
    Ok(())
}

/// Prepare email by adding default from address if needed.
fn prepare_email(email: &Email) -> Email {
    if email.from.is_none() {
        if let Some(from) = default_from() {
            let mut e = email.clone();
            e.from = Some(from);
            return e;
        }
    }
    email.clone()
}

/// Deliver an email using the global mailer.
///
/// Auto-configures from environment variables on first call.
/// Validates required fields (`from`, `to`) before sending.
/// Adds default `from` address from `EMAIL_FROM` if not set on email.
///
/// ```rust,ignore
/// use missive::{Email, deliver};
///
/// let email = Email::new()
///     .to("user@example.com")
///     .subject("Hello!")
///     .text_body("Hi there");
///
/// deliver(&email).await?;
/// ```
pub async fn deliver(email: &Email) -> Result<DeliveryResult, MailError> {
    // Validate required fields early
    validate(email)?;

    let mailer = get_mailer()?;
    let provider = mailer.provider_name();
    let email = prepare_email(email);

    // Emit telemetry span
    let span = tracing::info_span!(
        "missive.deliver",
        provider = provider,
        to = ?email.to.iter().map(|a| &a.email).collect::<Vec<_>>(),
        subject = %email.subject,
    );
    let _guard = span.enter();

    tracing::debug!("Delivering email");

    #[cfg(feature = "metrics")]
    let start = Instant::now();

    let result = mailer.deliver(&email).await;

    // Record metrics
    #[cfg(feature = "metrics")]
    {
        let duration = start.elapsed().as_secs_f64();
        let status = if result.is_ok() { "success" } else { "error" };
        metrics::counter!("missive_emails_total", "provider" => provider, "status" => status)
            .increment(1);
        metrics::histogram!("missive_delivery_duration_seconds", "provider" => provider)
            .record(duration);
    }

    match &result {
        Ok(r) => tracing::info!(message_id = %r.message_id, "Email delivered"),
        Err(e) => tracing::error!(error = %e, "Email delivery failed"),
    }

    result
}

/// Deliver an email using a specific mailer (per-call override).
///
/// Useful for testing or sending via a different provider.
///
/// ```rust,ignore
/// use missive::{Email, deliver_with};
/// use missive::providers::ResendMailer;
///
/// let mailer = ResendMailer::new("different_api_key");
/// let email = Email::new()
///     .to("user@example.com")
///     .subject("Hello!");
///
/// deliver_with(&email, &mailer).await?;
/// ```
pub async fn deliver_with<M: Mailer>(
    email: &Email,
    mailer: &M,
) -> Result<DeliveryResult, MailError> {
    // Validate required fields early
    validate(email)?;

    let provider = mailer.provider_name();
    let email = prepare_email(email);

    // Emit telemetry span
    let span = tracing::info_span!(
        "missive.deliver",
        provider = provider,
        to = ?email.to.iter().map(|a| &a.email).collect::<Vec<_>>(),
        subject = %email.subject,
    );
    let _guard = span.enter();

    tracing::debug!("Delivering email");

    #[cfg(feature = "metrics")]
    let start = Instant::now();

    let result = mailer.deliver(&email).await;

    // Record metrics
    #[cfg(feature = "metrics")]
    {
        let duration = start.elapsed().as_secs_f64();
        let status = if result.is_ok() { "success" } else { "error" };
        metrics::counter!("missive_emails_total", "provider" => provider, "status" => status)
            .increment(1);
        metrics::histogram!("missive_delivery_duration_seconds", "provider" => provider)
            .record(duration);
    }

    match &result {
        Ok(r) => tracing::info!(message_id = %r.message_id, "Email delivered"),
        Err(e) => tracing::error!(error = %e, "Email delivery failed"),
    }

    result
}

/// Deliver multiple emails using the global mailer.
pub async fn deliver_many(emails: &[Email]) -> Result<Vec<DeliveryResult>, MailError> {
    // Validate all emails first
    for email in emails {
        validate(email)?;
    }

    let mailer = get_mailer()?;
    let provider = mailer.provider_name();
    let count = emails.len();
    let emails: Vec<Email> = emails.iter().map(prepare_email).collect();

    let span = tracing::info_span!("missive.deliver_many", provider = provider, count = count,);
    let _guard = span.enter();

    #[cfg(feature = "metrics")]
    let start = Instant::now();

    let result = mailer.deliver_many(&emails).await;

    // Record metrics
    #[cfg(feature = "metrics")]
    {
        let duration = start.elapsed().as_secs_f64();
        let status = if result.is_ok() { "success" } else { "error" };
        metrics::counter!("missive_emails_total", "provider" => provider, "status" => status)
            .increment(count as u64);
        metrics::counter!("missive_batch_total", "provider" => provider, "status" => status)
            .increment(1);
        metrics::histogram!("missive_delivery_duration_seconds", "provider" => provider, "batch" => "true").record(duration);
        metrics::histogram!("missive_batch_size", "provider" => provider).record(count as f64);
    }

    result
}

// ============================================================================
// Manual Configuration (for testing or custom setups)
// ============================================================================

/// Manually configure the global mailer.
///
/// Sets a single global mailer used by `deliver()`.
/// Can be called multiple times - later calls replace the previous mailer.
///
/// ```rust,ignore
/// use missive::{configure, providers::LocalMailer};
///
/// configure(LocalMailer::new());
/// ```
pub fn configure<M: Mailer + 'static>(mailer: M) {
    let mut guard = MAILER.write();
    *guard = Some(Arc::new(mailer));
}

/// Configure with an Arc'd mailer.
pub fn configure_arc(mailer: Arc<dyn Mailer>) {
    let mut guard = MAILER.write();
    *guard = Some(mailer);
}

/// Reset the global mailer (useful for tests).
///
/// After calling this, the next `deliver()` will re-initialize from env vars.
pub fn reset() {
    let mut guard = MAILER.write();
    *guard = None;
}

/// Get a reference to the configured mailer (if initialized).
pub fn mailer() -> Option<Arc<dyn Mailer>> {
    let guard = MAILER.read();
    guard.as_ref().cloned()
}

/// Prelude module for convenient imports.
pub mod prelude {
    pub use crate::Address;
    pub use crate::Attachment;
    pub use crate::DeliveryResult;
    pub use crate::Email;
    pub use crate::MailError;
    pub use crate::Mailer;
    pub use crate::ToAddress;
    pub use crate::{default_from, deliver, deliver_many, deliver_with, is_configured};

    #[cfg(feature = "local")]
    pub use crate::Storage;
}