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
# Templates

Missive integrates with [Askama](https://github.com/djc/askama) for type-safe email templates.

## Setup

Enable the `templates` feature:

```toml
[dependencies]
missive = { version = "0.4", features = ["resend", "templates"] }
askama = "0.13"
```

## Basic Usage

There are two ways to use templates with Missive:

1. **`EmailTemplate` trait** - Define subject and recipient in the template struct
2. **Manual rendering** - Render the template yourself and pass to `Email`

### Using EmailTemplate Trait

The `EmailTemplate` trait lets you encapsulate all email details in one struct:

```html
<!-- templates/welcome.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to {{ app_name }}</title>
</head>
<body>
    <h1>Welcome, {{ username }}!</h1>
    <p>Thanks for signing up. Click below to verify your email:</p>
    <a href="{{ verify_url }}">Verify Email</a>
</body>
</html>
```

```rust
use askama::Template;
use missive::{Address, EmailTemplate};

#[derive(Template)]
#[template(path = "welcome.html")]
struct WelcomeEmail {
    app_name: String,
    username: String,
    verify_url: String,
    recipient: String,
}

impl EmailTemplate for WelcomeEmail {
    fn subject(&self) -> String {
        format!("Welcome to {}!", self.app_name)
    }

    fn to(&self) -> Address {
        self.recipient.as_str().into()
    }
}
```

Convert to `Email` and send:

```rust
let template = WelcomeEmail {
    app_name: "My App".to_string(),
    username: "Alice".to_string(),
    verify_url: "https://example.com/verify?token=abc123".to_string(),
    recipient: "alice@example.com".to_string(),
};

let email = template.into_email()?;
missive::deliver(&email).await?;
```

### Manual Rendering

For more control, render templates manually:

```rust
use askama::Template;
use missive::Email;

#[derive(Template)]
#[template(path = "welcome.html")]
struct WelcomeTemplate {
    app_name: String,
    username: String,
    verify_url: String,
}

let template = WelcomeTemplate {
    app_name: "My App".to_string(),
    username: "Alice".to_string(),
    verify_url: "https://example.com/verify?token=abc123".to_string(),
};

let html = template.render()?;

let email = Email::new()
    .to("alice@example.com")
    .subject("Welcome to My App!")
    .html_body(&html);

missive::deliver(&email).await?;
```

## EmailTemplate Options

The `EmailTemplate` trait has optional methods you can override:

```rust
impl EmailTemplate for WelcomeEmail {
    fn subject(&self) -> String {
        "Welcome!".to_string()
    }

    fn to(&self) -> Address {
        self.recipient.as_str().into()
    }

    // Optional: Set the sender
    fn from(&self) -> Option<Address> {
        Some(("My App", "hello@myapp.com").into())
    }

    // Optional: Set reply-to
    fn reply_to(&self) -> Option<Address> {
        Some("support@myapp.com".into())
    }

    // Optional: Add CC recipients
    fn cc(&self) -> Vec<Address> {
        vec!["team@myapp.com".into()]
    }

    // Optional: Add BCC recipients
    fn bcc(&self) -> Vec<Address> {
        vec![]
    }
}
```

## Both HTML and Text

For better deliverability, provide both HTML and plain text versions.

### With EmailTemplate

Use `into_email_with_text()` from the `EmailTemplateExt` trait:

```rust
use askama::Template;
use missive::{Address, EmailTemplate, EmailTemplateExt};

#[derive(Template)]
#[template(path = "welcome.html")]
struct WelcomeEmail {
    username: String,
    verify_url: String,
    recipient: String,
}

impl EmailTemplate for WelcomeEmail {
    fn subject(&self) -> String {
        "Welcome!".to_string()
    }

    fn to(&self) -> Address {
        self.recipient.as_str().into()
    }
}

// Create a separate text template
#[derive(Template)]
#[template(path = "welcome.txt")]
struct WelcomeText {
    username: String,
    verify_url: String,
}

let html_template = WelcomeEmail {
    username: "Alice".to_string(),
    verify_url: "https://example.com/verify".to_string(),
    recipient: "alice@example.com".to_string(),
};

let text_template = WelcomeText {
    username: "Alice".to_string(),
    verify_url: "https://example.com/verify".to_string(),
};

let text_body = text_template.render()?;
let email = html_template.into_email_with_text(&text_body)?;
```

### With Manual Rendering

```rust
#[derive(Template)]
#[template(path = "welcome.html")]
struct WelcomeHtml {
    username: String,
    verify_url: String,
}

#[derive(Template)]
#[template(path = "welcome.txt")]
struct WelcomeText {
    username: String,
    verify_url: String,
}

let html = WelcomeHtml { /* ... */ }.render()?;
let text = WelcomeText { /* ... */ }.render()?;

let email = Email::new()
    .to("alice@example.com")
    .subject("Welcome!")
    .html_body(&html)
    .text_body(&text);
```

Example templates:

```html
<!-- templates/welcome.html -->
<h1>Welcome, {{ username }}!</h1>
<a href="{{ verify_url }}">Verify</a>
```

```text
<!-- templates/welcome.txt -->
Welcome, {{ username }}!

Verify: {{ verify_url }}
```

## Template Location

By default, Askama looks for templates in a `templates/` directory at your crate root:

```
my-app/
├── Cargo.toml
├── src/
│   └── main.rs
└── templates/
    ├── welcome.html
    ├── welcome.txt
    └── password_reset.html
```

Configure in `askama.toml` if needed:

```toml
[general]
dirs = ["templates", "emails"]
```

## Template Inheritance

Use Askama's template inheritance for consistent layouts:

```html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: sans-serif; }
        .container { max-width: 600px; margin: 0 auto; }
        .footer { color: #666; font-size: 12px; }
    </style>
</head>
<body>
    <div class="container">
        {% block content %}{% endblock %}

        <div class="footer">
            <p>© 2024 {{ company_name }}</p>
            <p><a href="{{ unsubscribe_url }}">Unsubscribe</a></p>
        </div>
    </div>
</body>
</html>
```

```html
<!-- templates/welcome.html -->
{% extends "base.html" %}

{% block content %}
<h1>Welcome, {{ username }}!</h1>
<p>Thanks for joining us.</p>
{% endblock %}
```

```rust
#[derive(Template)]
#[template(path = "welcome.html")]
struct WelcomeEmail {
    username: String,
    company_name: String,
    unsubscribe_url: String,
    recipient: String,
}

impl EmailTemplate for WelcomeEmail {
    fn subject(&self) -> String {
        format!("Welcome, {}!", self.username)
    }

    fn to(&self) -> Address {
        self.recipient.as_str().into()
    }
}
```

## Inline Styles

Email clients have limited CSS support. Use inline styles or a CSS inliner:

```rust
// Option 1: Inline styles in template
// <h1 style="color: #333; font-size: 24px;">Welcome</h1>

// Option 2: Use css-inline crate
use css_inline::inline;

let html = template.render()?;
let inlined = inline(&html)?;

let email = Email::new()
    .to("user@example.com")
    .subject("Welcome!")
    .html_body(inlined);
```

## Dynamic Content

Askama supports loops, conditionals, and filters:

```html
<h1>Your Order #{{ order_id }}</h1>

<table>
    {% for item in items %}
    <tr>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>${{ item.price|fmt("{:.2}") }}</td>
    </tr>
    {% endfor %}
</table>

<p><strong>Total: ${{ total|fmt("{:.2}") }}</strong></p>

{% if has_discount %}
<p>Discount applied: {{ discount_code }}</p>
{% endif %}
```

## Error Handling

Template rendering can fail. Handle errors appropriately:

```rust
use missive::MailError;

let template = WelcomeEmail { /* ... */ };

match template.into_email() {
    Ok(email) => {
        missive::deliver(&email).await?;
    }
    Err(MailError::TemplateError(e)) => {
        tracing::error!("Template rendering failed: {}", e);
        // Maybe send a fallback plain text email
    }
    Err(e) => return Err(e),
}
```

## Testing Templates

Test template rendering without sending:

```rust
#[test]
fn test_welcome_template() {
    let template = WelcomeEmail {
        username: "Alice".to_string(),
        verify_url: "https://example.com/verify".to_string(),
        recipient: "alice@example.com".to_string(),
    };

    // Test raw rendering
    let html = template.render().unwrap();
    assert!(html.contains("Welcome, Alice!"));
    assert!(html.contains("https://example.com/verify"));
}

#[test]
fn test_email_conversion() {
    let template = WelcomeEmail {
        username: "Alice".to_string(),
        verify_url: "https://example.com/verify".to_string(),
        recipient: "alice@example.com".to_string(),
    };

    let email = template.into_email().unwrap();
    assert_eq!(email.subject, "Welcome!");
    assert!(email.html_body.unwrap().contains("Alice"));
}
```

## Organize Email Templates

Suggested structure for larger apps:

```
src/
├── emails/
│   ├── mod.rs
│   ├── welcome.rs
│   ├── password_reset.rs
│   └── order_confirmation.rs
└── main.rs

templates/
├── emails/
│   ├── base.html
│   ├── welcome.html
│   ├── welcome.txt
│   ├── password_reset.html
│   └── order_confirmation.html
```

```rust
// src/emails/mod.rs
mod welcome;
mod password_reset;

pub use welcome::send_welcome_email;
pub use password_reset::send_password_reset;
```

```rust
// src/emails/welcome.rs
use askama::Template;
use missive::{Address, EmailTemplate, deliver};

#[derive(Template)]
#[template(path = "emails/welcome.html")]
struct WelcomeEmail {
    username: String,
    verify_url: String,
    recipient: String,
}

impl EmailTemplate for WelcomeEmail {
    fn subject(&self) -> String {
        "Welcome!".to_string()
    }

    fn to(&self) -> Address {
        self.recipient.as_str().into()
    }
}

pub async fn send_welcome_email(
    to: &str,
    username: &str,
    verify_url: &str,
) -> Result<(), missive::MailError> {
    let template = WelcomeEmail {
        username: username.to_string(),
        verify_url: verify_url.to_string(),
        recipient: to.to_string(),
    };

    let email = template.into_email()?;
    deliver(&email).await?;
    Ok(())
}
```