simplemailclient 0.2.0

A simple terminal mail client (SMTP send, IMAP fetch) with a TUI.
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
use anyhow::{bail, Context, Result};
use base64::Engine;
use lettre::{
    message::{header::ContentType, Attachment, Message as LettreMessage, MultiPart, SinglePart},
    transport::smtp::authentication::Credentials,
    AsyncSmtpTransport, AsyncTransport, Tokio1Executor,
};
use crate::config::Config;
use crate::store::{Attachment as StoreAttachment, MailStore};

pub const MAIL_SUBJECT: &str = "[mailrs_mail]";

/// Maximum size for a single attachment (25 MB).
pub const MAX_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;

// ─── SMTP Send ────────────────────────────────────────────────────────────────

/// Send a message. `attachments` is a list of file paths; each is sent as a
/// separate MIME part (proper `Content-Disposition: attachment`), kept fully
/// distinct from the body text. Binary files (zip, images, …) are supported.
pub async fn send_smtp(cfg: &Config, to: &str, body: &str, attachments: &[String]) -> Result<()> {
    let from_addr = match &cfg.display_name {
        Some(name) => format!("{} <{}>", name, cfg.identity),
        None => cfg.identity.clone(),
    };

    let builder = LettreMessage::builder()
        .from(from_addr.parse().context("Invalid from address")?)
        .to(to.parse().context("Invalid to address")?)
        .subject(MAIL_SUBJECT);

    let email = if attachments.is_empty() {
        // Plain single-part message (no MIME multipart needed).
        builder
            .body(body.to_string())
            .context("Failed to build email")?
    } else {
        // multipart/mixed: an inline text body, then one part per file.
        // The body is its own SinglePart (inline); each file gets a proper
        // Content-Disposition: attachment header so receivers — including this
        // client — keep it separate from the message text.
        let mut mp = MultiPart::mixed().singlepart(SinglePart::plain(body.to_string()));

        for path in attachments {
            let data = std::fs::read(path)
                .with_context(|| format!("Cannot read attachment: {}", path))?;
            if data.len() as u64 > MAX_ATTACHMENT_BYTES {
                bail!("Attachment exceeds 25 MB limit: {}", path);
            }
            let filename = std::path::Path::new(path)
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| "attachment".to_string());
            // Always use application/octet-stream so every mail client
            // (Gmail, Outlook, …) treats the file as a downloadable attachment
            // rather than rendering it inline.  The real MIME type is preserved
            // in the filename extension; clients use that for icons and openers.
            let ct = ContentType::parse("application/octet-stream").unwrap();
            mp = mp.singlepart(Attachment::new(filename).body(data, ct));
        }

        builder.multipart(mp).context("Failed to build email")?
    };

    let creds = Credentials::new(
        cfg.smtp.username.clone(),
        cfg.smtp.password.clone(),
    );

    let transport: AsyncSmtpTransport<Tokio1Executor> = if cfg.smtp.tls {
        AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&cfg.smtp.host)
            .context("SMTP STARTTLS relay failed")?
            .port(cfg.smtp.port)
            .credentials(creds)
            .build()
    } else {
        AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&cfg.smtp.host)
            .port(cfg.smtp.port)
            .credentials(creds)
            .build()
    };

    transport
        .send(email)
        .await
        .context("SMTP send failed")?;

    Ok(())
}

// ─── IMAP Fetch ───────────────────────────────────────────────────────────────

pub async fn fetch_imap(cfg: &Config, store: &MailStore) -> Result<()> {
    use std::net::TcpStream;
    use native_tls::TlsConnector;
    use imap::Client;

    let domain = cfg.imap.host.clone();
    let port = cfg.imap.port;

    let tls = TlsConnector::builder()
        .build()
        .context("TLS connector failed")?;

    let addr = format!("{}:{}", domain, port);
    let stream = TcpStream::connect(&addr)
        .context("TCP connection failed")?;

    let tls_stream = tls.connect(&domain, stream)
        .context("IMAP TLS handshake failed")?;

    let client = Client::new(tls_stream);

    let mut imap_session = client
        .login(&cfg.imap.username, &cfg.imap.password)
        .map_err(|(err, _)| err)
        .context("IMAP login failed")?;

    imap_session
        .select(&cfg.imap.inbox_folder)
        .context("IMAP SELECT failed")?;

    // Fetch all messages (read or unread) with our marker subject — keeps full history
    let uids_set = imap_session
        .uid_search(format!("SUBJECT \"{}\"", MAIL_SUBJECT))
        .context("IMAP SEARCH failed")?;

    if uids_set.is_empty() {
        imap_session.logout().ok();
        return Ok(());
    }

    // Convert to sorted vec and keep only the last 50 (most recent)
    let mut uids: Vec<u32> = uids_set.into_iter().collect();
    uids.sort();
    if uids.len() > 50 {
        uids = uids.into_iter().rev().take(50).collect::<Vec<_>>();
        uids.reverse(); // Re-sort ascending for IMAP
    }

    let uid_set: String = uids
        .iter()
        .map(|u| u.to_string())
        .collect::<Vec<_>>()
        .join(",");

    let messages = imap_session
        .uid_fetch(&uid_set, "(RFC822 ENVELOPE)")
        .context("IMAP FETCH failed")?;

    for raw in messages.iter() {
        // Parse sender from envelope
        let (from_addr, display_name) = if let Some(envelope) = raw.envelope() {
            parse_envelope_from(envelope)
        } else {
            ("unknown@unknown".to_string(), None)
        };

        let uid = raw.uid; // field, not method

        // Parse body text + collect attachments separately from the body
        let (body, message_id, attachments) = if let Some(bytes) = raw.body() {
            let body_text = extract_body_text(bytes);
            let mid = extract_message_id(bytes);
            let atts = extract_attachments(bytes);
            (body_text, mid, atts)
        } else {
            (String::new(), None, Vec::new())
        };

        // Skip truly empty messages (no body and no files)
        if body.is_empty() && attachments.is_empty() {
            continue;
        }

        store.deliver(&from_addr, &body, display_name.as_deref(), uid, message_id, attachments)?;
    }

    imap_session.logout().ok();
    Ok(())
}

// ─── IMAP Trash Move ──────────────────────────────────────────────────────────

/// Move a message by UID from the inbox to the configured trash folder on the
/// IMAP server.  This is a best-effort operation — the caller should still
/// update local state regardless of whether this succeeds.
pub async fn imap_move_to_trash(cfg: &Config, uid: u32) -> Result<()> {
    use std::net::TcpStream;
    use native_tls::TlsConnector;
    use imap::Client;

    let domain = cfg.imap.host.clone();
    let port = cfg.imap.port;

    let tls = TlsConnector::builder()
        .build()
        .context("TLS connector failed")?;

    let addr = format!("{}:{}", domain, port);
    let stream = TcpStream::connect(&addr)
        .context("TCP connection failed")?;

    let tls_stream = tls.connect(&domain, stream)
        .context("IMAP TLS handshake failed")?;

    let client = Client::new(tls_stream);

    let mut session = client
        .login(&cfg.imap.username, &cfg.imap.password)
        .map_err(|(err, _)| err)
        .context("IMAP login failed")?;

    session
        .select(&cfg.imap.inbox_folder)
        .context("IMAP SELECT failed")?;

    let uid_str = uid.to_string();

    // COPY to trash folder, then mark original as \Deleted and expunge
    session
        .uid_copy(&uid_str, &cfg.imap.trash_folder)
        .context("IMAP UID COPY to trash failed")?;

    session
        .uid_store(&uid_str, "+FLAGS (\\Deleted)")
        .context("IMAP UID STORE \\Deleted failed")?;

    session.expunge().context("IMAP EXPUNGE failed")?;

    session.logout().ok();
    Ok(())
}

// ─── MIME helpers ─────────────────────────────────────────────────────────────

/// Clean a body string that was previously stored as a raw MIME fragment
/// (body-only, no outer RFC822 headers). Reconstructs the missing outer
/// headers by detecting the boundary from the first `--<id>` line, then
/// delegates to the normal extractor.
pub fn extract_body_text_pub(raw: &[u8]) -> String {
    let text = String::from_utf8_lossy(raw);

    // Find the boundary: the first line starting with "--" followed by
    // non-whitespace hex characters.
    let boundary = text.lines().find_map(|line| {
        let line = line.trim();
        if line.starts_with("--") && line.len() > 2 && !line.ends_with("--") {
            Some(line[2..].to_string())
        } else {
            None
        }
    });

    if let Some(b) = boundary {
        let wrapped = format!(
            "From: x\r\nMIME-Version: 1.0\r\nContent-Type: multipart/alternative; boundary=\"{}\"\r\n\r\n{}",
            b, text
        );
        let result = extract_body_text(wrapped.as_bytes());
        if !result.is_empty() {
            return result;
        }
    }

    // Not actually MIME multipart — return as-is.
    text.trim().to_string()
}

/// Extract the readable plain-text body from a raw RFC822 message.
///
/// Handles MIME multipart (preferring the `text/plain` part), and decodes
/// transfer encodings (quoted-printable / base64) and charset via `mailparse`.
/// Falls back to naive header-stripping if the message can't be parsed.
fn extract_body_text(raw: &[u8]) -> String {
    match mailparse::parse_mail(raw) {
        Ok(parsed) => extract_text_from_part(&parsed)
            .map(|s| s.trim().to_string())
            .unwrap_or_default(),
        Err(_) => {
            let text = String::from_utf8_lossy(raw);
            if let Some(pos) = text.find("\r\n\r\n") {
                text[pos + 4..].trim().to_string()
            } else if let Some(pos) = text.find("\n\n") {
                text[pos + 2..].trim().to_string()
            } else {
                text.trim().to_string()
            }
        }
    }
}

/// Walk a parsed MIME tree and return the best text body: prefer `text/plain`,
/// then any other `text/*` part, recursing into nested multiparts.
/// Crucially, parts marked as attachments are skipped so an attached text file
/// never gets mistaken for the message body.
fn extract_text_from_part(part: &mailparse::ParsedMail) -> Option<String> {
    if part.subparts.is_empty() {
        // Leaf part: return its decoded body if it's textual and not an attachment.
        if part.ctype.mimetype.starts_with("text/") && !is_attachment(part) {
            if let Ok(body) = part.get_body() {
                if !body.trim().is_empty() {
                    return Some(body);
                }
            }
        }
        return None;
    }

    // Multipart: first pass prefers a non-attachment text/plain part.
    for sp in &part.subparts {
        if sp.ctype.mimetype == "text/plain" && !is_attachment(sp) {
            if let Ok(body) = sp.get_body() {
                if !body.trim().is_empty() {
                    return Some(body);
                }
            }
        }
    }
    // Second pass: recurse (handles multipart/alternative and the like).
    for sp in &part.subparts {
        if let Some(body) = extract_text_from_part(sp) {
            return Some(body);
        }
    }
    None
}

/// Decide whether a MIME part is an attachment.
///
/// The reliable marker is `Content-Disposition: attachment` (which is what
/// lettre — and most mailers — emit). We also treat any part carrying a
/// filename/name parameter as an attachment, regardless of MIME type. This is
/// the fix for the old bug where an attached `.txt` file's contents leaked into
/// the message body: previously only the Content-Type `filename` param was
/// checked, but the filename actually lives in Content-Disposition.
fn is_attachment(part: &mailparse::ParsedMail) -> bool {
    let cd = part.get_content_disposition();
    if cd.disposition == mailparse::DispositionType::Attachment {
        return true;
    }
    if cd.params.contains_key("filename") {
        return true;
    }
    // Some senders put the name on the Content-Type instead.
    part.ctype.params.contains_key("name") || part.ctype.params.contains_key("filename")
}

/// Resolve an attachment's filename from Content-Disposition (preferred) or the
/// Content-Type `name` parameter, falling back to a generic name.
fn attachment_filename(part: &mailparse::ParsedMail) -> String {
    let cd = part.get_content_disposition();
    if let Some(f) = cd.params.get("filename") {
        return f.clone();
    }
    if let Some(n) = part.ctype.params.get("name") {
        return n.clone();
    }
    if let Some(f) = part.ctype.params.get("filename") {
        return f.clone();
    }
    "attachment.bin".to_string()
}

/// Extract all attachments from a raw RFC822 message, base64-encoding their
/// decoded bytes for storage.
fn extract_attachments(raw: &[u8]) -> Vec<StoreAttachment> {
    match mailparse::parse_mail(raw) {
        Ok(parsed) => collect_attachments_from_part(&parsed),
        Err(_) => Vec::new(),
    }
}

/// Recursively collect attachment parts (anything `is_attachment` flags) from a
/// MIME tree.
fn collect_attachments_from_part(part: &mailparse::ParsedMail) -> Vec<StoreAttachment> {
    let mut attachments = Vec::new();

    // Recurse into multiparts first.
    for sp in &part.subparts {
        attachments.extend(collect_attachments_from_part(sp));
    }

    // Leaf attachment part → store it.
    if part.subparts.is_empty() && is_attachment(part) {
        if let Ok(data) = part.get_body_raw() {
            let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
            attachments.push(StoreAttachment {
                filename: attachment_filename(part),
                size: data.len() as u64,
                mime_type: part.ctype.mimetype.clone(),
                data: encoded,
            });
        }
    }

    attachments
}

/// Extract the RFC 2822 Message-ID header from a raw message, if present.
fn extract_message_id(raw: &[u8]) -> Option<String> {
    match mailparse::parse_mail(raw) {
        Ok(parsed) => parsed
            .headers
            .iter()
            .find(|h| h.get_key_ref().eq_ignore_ascii_case("message-id"))
            .map(|h| h.get_value().trim().to_string()),
        Err(_) => {
            // Fallback: scan the raw bytes for the header line
            let text = String::from_utf8_lossy(raw);
            for line in text.lines() {
                if line.to_ascii_lowercase().starts_with("message-id:") {
                    return Some(line[11..].trim().to_string());
                }
                // Stop at blank line (end of headers)
                if line.trim().is_empty() {
                    break;
                }
            }
            None
        }
    }
}

/// Guess a MIME type from a file path's extension.
pub fn guess_mime(path: &str) -> &'static str {
    let ext = std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    match ext.as_str() {
        "txt" | "log" | "text" => "text/plain",
        "md"                    => "text/markdown",
        "csv"                   => "text/csv",
        "html" | "htm"          => "text/html",
        "json"                  => "application/json",
        "xml"                   => "application/xml",
        "pdf"                   => "application/pdf",
        "zip"                   => "application/zip",
        "gz" | "tgz"            => "application/gzip",
        "tar"                   => "application/x-tar",
        "7z"                    => "application/x-7z-compressed",
        "rar"                   => "application/vnd.rar",
        "doc"                   => "application/msword",
        "docx"                  => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xls"                   => "application/vnd.ms-excel",
        "xlsx"                  => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "png"                   => "image/png",
        "jpg" | "jpeg"          => "image/jpeg",
        "gif"                   => "image/gif",
        "webp"                  => "image/webp",
        "svg"                   => "image/svg+xml",
        "mp3"                   => "audio/mpeg",
        "mp4"                   => "video/mp4",
        _                       => "application/octet-stream",
    }
}

/// Pull the first From address out of an IMAP envelope.
fn parse_envelope_from(envelope: &imap_proto::types::Envelope) -> (String, Option<String>) {
    if let Some(addresses) = &envelope.from {
        if let Some(addr) = addresses.first() {
            let mailbox = addr
                .mailbox
                .as_ref()
                .map(|b| String::from_utf8_lossy(b).to_string())
                .unwrap_or_default();
            let host = addr
                .host
                .as_ref()
                .map(|b| String::from_utf8_lossy(b).to_string())
                .unwrap_or_default();
            let name = addr.name.as_ref().map(|b| String::from_utf8_lossy(b).to_string());
            return (format!("{}@{}", mailbox, host), name);
        }
    }
    ("unknown@unknown".to_string(), None)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mime_migration() {
        let raw = "--000000000000626b900653087fa1\r\nContent-Type: text/plain; charset=\"UTF-8\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nRem sama sana duydu=C4=9Fum duygular...\r\n\r\n--000000000000626b900653087fa1\r\nContent-Type: text/html; charset=\"UTF-8\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n<div>Rem sama sana duydu=C4=9Fum duygular...</div>\r\n\r\n--000000000000626b900653087fa1--\r\n";
        let result = extract_body_text_pub(raw.as_bytes());
        assert_eq!(result, "Rem sama sana duyduğum duygular...", "got: {:?}", result);
    }

    /// The core regression test for the "ek metin testi" bug: a message with a
    /// text body AND an attached text file must return the BODY, not the file
    /// contents, and the attachment must be collected separately.
    #[test]
    fn test_body_vs_text_attachment() {
        let raw = "From: a@b.com\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"BOUND\"\r\n\r\n--BOUND\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nThis is the real body.\r\n--BOUND\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Disposition: attachment; filename=\"notes.txt\"\r\n\r\nek metin testi\r\n--BOUND--\r\n";
        let body = extract_body_text(raw.as_bytes());
        assert_eq!(body, "This is the real body.", "body got: {:?}", body);

        let atts = extract_attachments(raw.as_bytes());
        assert_eq!(atts.len(), 1, "expected exactly one attachment");
        assert_eq!(atts[0].filename, "notes.txt");
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&atts[0].data)
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&decoded).trim(), "ek metin testi");
    }
}