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
//! # SMTP transport module.

pub mod send;

use std::time::Duration;

use anyhow::{bail, format_err, Context as _, Error, Result};
use async_smtp::response::{Category, Code, Detail};
use async_smtp::{self as smtp, EmailAddress, SmtpTransport};
use tokio::io::BufStream;
use tokio::task;

use crate::chat::{add_info_msg_with_cmd, ChatId};
use crate::config::Config;
use crate::contact::{Contact, ContactId};
use crate::context::Context;
use crate::events::EventType;
use crate::login_param::{CertificateChecks, LoginParam, ServerLoginParam};
use crate::message::Message;
use crate::message::{self, MsgId};
use crate::mimefactory::MimeFactory;
use crate::net::connect_tcp;
use crate::net::session::SessionBufStream;
use crate::net::tls::wrap_tls;
use crate::oauth2::get_oauth2_access_token;
use crate::provider::Socket;
use crate::scheduler::connectivity::ConnectivityStore;
use crate::socks::Socks5Config;
use crate::sql;
use crate::stock_str::unencrypted_email;
use crate::tools::{self, time_elapsed};

/// SMTP connection, write and read timeout.
const SMTP_TIMEOUT: Duration = Duration::from_secs(60);

#[derive(Default)]
pub(crate) struct Smtp {
    /// SMTP connection.
    transport: Option<SmtpTransport<Box<dyn SessionBufStream>>>,

    /// Email address we are sending from.
    from: Option<EmailAddress>,

    /// Timestamp of last successful send/receive network interaction
    /// (eg connect or send succeeded). On initialization and disconnect
    /// it is set to None.
    last_success: Option<tools::Time>,

    pub(crate) connectivity: ConnectivityStore,

    /// If sending the last message failed, contains the error message.
    pub(crate) last_send_error: Option<String>,
}

impl Smtp {
    /// Create a new Smtp instances.
    pub fn new() -> Self {
        Default::default()
    }

    /// Disconnect the SMTP transport and drop it entirely.
    pub fn disconnect(&mut self) {
        if let Some(mut transport) = self.transport.take() {
            // Closing connection with a QUIT command may take some time, especially if it's a
            // stale connection and an attempt to send the command times out. Send a command in a
            // separate task to avoid waiting for reply or timeout.
            task::spawn(async move { transport.quit().await });
        }
        self.last_success = None;
    }

    /// Return true if smtp was connected but is not known to
    /// have been successfully used the last 60 seconds
    pub fn has_maybe_stale_connection(&self) -> bool {
        if let Some(last_success) = self.last_success {
            time_elapsed(&last_success).as_secs() > 60
        } else {
            false
        }
    }

    /// Check whether we are connected.
    pub fn is_connected(&self) -> bool {
        self.transport.is_some()
    }

    /// Connect using configured parameters.
    pub async fn connect_configured(&mut self, context: &Context) -> Result<()> {
        if self.has_maybe_stale_connection() {
            info!(context, "Closing stale connection.");
            self.disconnect();
        }

        if self.is_connected() {
            return Ok(());
        }

        self.connectivity.set_connecting(context).await;
        let lp = LoginParam::load_configured_params(context).await?;
        self.connect(
            context,
            &lp.smtp,
            &lp.socks5_config,
            &lp.addr,
            lp.provider.map_or(lp.socks5_config.is_some(), |provider| {
                provider.opt.strict_tls
            }),
        )
        .await
    }

    async fn connect_secure_socks5(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
        strict_tls: bool,
        socks5_config: Socks5Config,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let socks5_stream = socks5_config
            .connect(context, hostname, port, SMTP_TIMEOUT, strict_tls)
            .await?;
        let tls_stream = wrap_tls(strict_tls, hostname, &["smtp"], socks5_stream).await?;
        let buffered_stream = BufStream::new(tls_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    async fn connect_starttls_socks5(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
        strict_tls: bool,
        socks5_config: Socks5Config,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let socks5_stream = socks5_config
            .connect(context, hostname, port, SMTP_TIMEOUT, strict_tls)
            .await?;

        // Run STARTTLS command and convert the client back into a stream.
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, BufStream::new(socks5_stream)).await?;
        let tcp_stream = transport.starttls().await?.into_inner();
        let tls_stream = wrap_tls(strict_tls, hostname, &["smtp"], tcp_stream)
            .await
            .context("STARTTLS upgrade failed")?;
        let buffered_stream = BufStream::new(tls_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true).without_greeting();
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    async fn connect_insecure_socks5(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
        socks5_config: Socks5Config,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let socks5_stream = socks5_config
            .connect(context, hostname, port, SMTP_TIMEOUT, false)
            .await?;
        let buffered_stream = BufStream::new(socks5_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    async fn connect_secure(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
        strict_tls: bool,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let tcp_stream = connect_tcp(context, hostname, port, SMTP_TIMEOUT, false).await?;
        let tls_stream = wrap_tls(strict_tls, hostname, &["smtp"], tcp_stream).await?;
        let buffered_stream = BufStream::new(tls_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    async fn connect_starttls(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
        strict_tls: bool,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let tcp_stream = connect_tcp(context, hostname, port, SMTP_TIMEOUT, strict_tls).await?;

        // Run STARTTLS command and convert the client back into a stream.
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, BufStream::new(tcp_stream)).await?;
        let tcp_stream = transport.starttls().await?.into_inner();
        let tls_stream = wrap_tls(strict_tls, hostname, &["smtp"], tcp_stream)
            .await
            .context("STARTTLS upgrade failed")?;
        let buffered_stream = BufStream::new(tls_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true).without_greeting();
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    async fn connect_insecure(
        &self,
        context: &Context,
        hostname: &str,
        port: u16,
    ) -> Result<SmtpTransport<Box<dyn SessionBufStream>>> {
        let tcp_stream = connect_tcp(context, hostname, port, SMTP_TIMEOUT, false).await?;
        let buffered_stream = BufStream::new(tcp_stream);
        let session_stream: Box<dyn SessionBufStream> = Box::new(buffered_stream);
        let client = smtp::SmtpClient::new().smtp_utf8(true);
        let transport = SmtpTransport::new(client, session_stream).await?;
        Ok(transport)
    }

    /// Connect using the provided login params.
    pub async fn connect(
        &mut self,
        context: &Context,
        lp: &ServerLoginParam,
        socks5_config: &Option<Socks5Config>,
        addr: &str,
        provider_strict_tls: bool,
    ) -> Result<()> {
        if self.is_connected() {
            warn!(context, "SMTP already connected.");
            return Ok(());
        }

        if lp.server.is_empty() || lp.port == 0 {
            bail!("bad connection parameters");
        }

        let from = EmailAddress::new(addr.to_string())
            .with_context(|| format!("invalid login address {addr}"))?;

        self.from = Some(from);

        let domain = &lp.server;
        let port = lp.port;

        let strict_tls = match lp.certificate_checks {
            CertificateChecks::Automatic => provider_strict_tls,
            CertificateChecks::Strict => true,
            CertificateChecks::AcceptInvalidCertificates
            | CertificateChecks::AcceptInvalidCertificates2 => false,
        };

        let mut transport = if let Some(socks5_config) = socks5_config {
            match lp.security {
                Socket::Automatic => bail!("SMTP port security is not configured"),
                Socket::Ssl => {
                    self.connect_secure_socks5(
                        context,
                        domain,
                        port,
                        strict_tls,
                        socks5_config.clone(),
                    )
                    .await?
                }
                Socket::Starttls => {
                    self.connect_starttls_socks5(
                        context,
                        domain,
                        port,
                        strict_tls,
                        socks5_config.clone(),
                    )
                    .await?
                }
                Socket::Plain => {
                    self.connect_insecure_socks5(context, domain, port, socks5_config.clone())
                        .await?
                }
            }
        } else {
            match lp.security {
                Socket::Automatic => bail!("SMTP port security is not configured"),
                Socket::Ssl => {
                    self.connect_secure(context, domain, port, strict_tls)
                        .await?
                }
                Socket::Starttls => {
                    self.connect_starttls(context, domain, port, strict_tls)
                        .await?
                }
                Socket::Plain => self.connect_insecure(context, domain, port).await?,
            }
        };

        // Authenticate.
        {
            let (creds, mechanism) = if lp.oauth2 {
                // oauth2
                let send_pw = &lp.password;
                let access_token = get_oauth2_access_token(context, addr, send_pw, false).await?;
                if access_token.is_none() {
                    bail!("SMTP OAuth 2 error {}", addr);
                }
                let user = &lp.user;
                (
                    smtp::authentication::Credentials::new(
                        user.to_string(),
                        access_token.unwrap_or_default(),
                    ),
                    vec![smtp::authentication::Mechanism::Xoauth2],
                )
            } else {
                // plain
                let user = lp.user.clone();
                let pw = lp.password.clone();
                (
                    smtp::authentication::Credentials::new(user, pw),
                    vec![
                        smtp::authentication::Mechanism::Plain,
                        smtp::authentication::Mechanism::Login,
                    ],
                )
            };
            transport.try_login(&creds, &mechanism).await?;
        }

        self.transport = Some(transport);
        self.last_success = Some(tools::Time::now());

        context.emit_event(EventType::SmtpConnected(format!(
            "SMTP-LOGIN as {} ok",
            lp.user,
        )));

        Ok(())
    }
}

pub(crate) enum SendResult {
    /// Message was sent successfully.
    Success,

    /// Permanent error, message sending has failed.
    Failure(Error),

    /// Temporary error, the message should be retried later.
    Retry,
}

/// Tries to send a message.
pub(crate) async fn smtp_send(
    context: &Context,
    recipients: &[async_smtp::EmailAddress],
    message: &str,
    smtp: &mut Smtp,
    msg_id: Option<MsgId>,
) -> SendResult {
    if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
        info!(context, "SMTP-sending out mime message:\n{message}");
    }

    smtp.connectivity.set_working(context).await;

    if let Err(err) = smtp
        .connect_configured(context)
        .await
        .context("Failed to open SMTP connection")
    {
        smtp.last_send_error = Some(format!("{err:#}"));
        return SendResult::Retry;
    }

    let send_result = smtp.send(context, recipients, message.as_bytes()).await;
    smtp.last_send_error = send_result.as_ref().err().map(|e| e.to_string());

    let status = match send_result {
        Err(crate::smtp::send::Error::SmtpSend(err)) => {
            // Remote error, retry later.
            info!(context, "SMTP failed to send: {:?}.", &err);

            let res = match err {
                async_smtp::error::Error::Permanent(ref response) => {
                    // Workaround for incorrectly configured servers returning permanent errors
                    // instead of temporary ones.
                    let maybe_transient = match response.code {
                        // Sometimes servers send a permanent error when actually it is a temporary error
                        // For documentation see <https://tools.ietf.org/html/rfc3463>
                        Code {
                            category: Category::MailSystem,
                            detail: Detail::Zero,
                            ..
                        } => {
                            // Ignore status code 5.5.0, see <https://support.delta.chat/t/every-other-message-gets-stuck/877/2>
                            // Maybe incorrectly configured Postfix milter with "reject" instead of "tempfail", which returns
                            // "550 5.5.0 Service unavailable" instead of "451 4.7.1 Service unavailable - try again later".
                            //
                            // Other enhanced status codes, such as Postfix
                            // "550 5.1.1 <foobar@example.org>: Recipient address rejected: User unknown in local recipient table"
                            // are not ignored.
                            response.first_word() == Some("5.5.0")
                        }
                        _ => false,
                    };

                    if maybe_transient {
                        info!(context, "Permanent error that is likely to actually be transient, postponing retry for later.");
                        SendResult::Retry
                    } else {
                        info!(context, "Permanent error, message sending failed.");
                        // If we do not retry, add an info message to the chat.
                        // Yandex error "554 5.7.1 [2] Message rejected under suspicion of SPAM; https://ya.cc/..."
                        // should definitely go here, because user has to open the link to
                        // resume message sending.
                        SendResult::Failure(format_err!("Permanent SMTP error: {}", err))
                    }
                }
                async_smtp::error::Error::Transient(ref response) => {
                    // We got a transient 4xx response from SMTP server.
                    // Give some time until the server-side error maybe goes away.

                    if let Some(first_word) = response.first_word() {
                        if first_word.ends_with(".1.1")
                            || first_word.ends_with(".1.2")
                            || first_word.ends_with(".1.3")
                        {
                            // Sometimes we receive transient errors that should be permanent.
                            // Any extended smtp status codes like x.1.1, x.1.2 or x.1.3 that we
                            // receive as a transient error are misconfigurations of the smtp server.
                            // See <https://tools.ietf.org/html/rfc3463#section-3.2>
                            info!(context, "Received extended status code {first_word} for a transient error. This looks like a misconfigured SMTP server, let's fail immediately.");
                            SendResult::Failure(format_err!("Permanent SMTP error: {}", err))
                        } else {
                            info!(
                                context,
                                "Transient error with status code {first_word}, postponing retry for later."
                            );
                            SendResult::Retry
                        }
                    } else {
                        info!(
                            context,
                            "Transient error without status code, postponing retry for later."
                        );
                        SendResult::Retry
                    }
                }
                _ => {
                    info!(
                        context,
                        "Message sending failed without error returned by the server, retry later."
                    );
                    SendResult::Retry
                }
            };

            // this clears last_success info
            info!(context, "Failed to send message over SMTP, disconnecting.");
            smtp.disconnect();

            res
        }
        Err(crate::smtp::send::Error::Envelope(err)) => {
            // Local error, job is invalid, do not retry.
            smtp.disconnect();
            warn!(context, "SMTP job is invalid: {err:#}.");
            SendResult::Failure(err)
        }
        Err(crate::smtp::send::Error::NoTransport) => {
            // Should never happen.
            // It does not even make sense to disconnect here.
            error!(context, "SMTP job failed because SMTP has no transport.");
            SendResult::Failure(format_err!("SMTP has not transport"))
        }
        Err(crate::smtp::send::Error::Other(err)) => {
            // Local error, job is invalid, do not retry.
            smtp.disconnect();
            warn!(context, "Unable to load SMTP job: {err:#}.");
            SendResult::Failure(err)
        }
        Ok(()) => SendResult::Success,
    };

    if let SendResult::Failure(err) = &status {
        if let Some(msg_id) = msg_id {
            // We couldn't send the message, so mark it as failed
            match Message::load_from_db(context, msg_id).await {
                Ok(mut msg) => {
                    if let Err(err) =
                        message::set_msg_failed(context, &mut msg, &err.to_string()).await
                    {
                        error!(context, "Failed to mark {msg_id} as failed: {err:#}.");
                    }
                }
                Err(err) => {
                    error!(
                        context,
                        "Failed to load {msg_id} to mark it as failed: {err:#}."
                    );
                }
            }
        }
    }
    status
}

/// Sends message identified by `smtp` table rowid over SMTP connection.
///
/// Removes row if the message should not be retried, otherwise increments retry count.
pub(crate) async fn send_msg_to_smtp(
    context: &Context,
    smtp: &mut Smtp,
    rowid: i64,
) -> anyhow::Result<()> {
    if let Err(err) = smtp
        .connect_configured(context)
        .await
        .context("SMTP connection failure")
    {
        smtp.last_send_error = Some(format!("{err:#}"));
        return Err(err);
    }

    // Increase retry count as soon as we have an SMTP connection. This ensures that the message is
    // eventually removed from the queue by exceeding retry limit even in case of an error that
    // keeps happening early in the message sending code, e.g. failure to read the message from the
    // database.
    context
        .sql
        .execute("UPDATE smtp SET retries=retries+1 WHERE id=?", (rowid,))
        .await
        .context("failed to update retries count")?;

    let (body, recipients, msg_id, retries) = context
        .sql
        .query_row(
            "SELECT mime, recipients, msg_id, retries FROM smtp WHERE id=?",
            (rowid,),
            |row| {
                let mime: String = row.get(0)?;
                let recipients: String = row.get(1)?;
                let msg_id: MsgId = row.get(2)?;
                let retries: i64 = row.get(3)?;
                Ok((mime, recipients, msg_id, retries))
            },
        )
        .await?;
    if retries > 6 {
        let mut msg = Message::load_from_db(context, msg_id).await?;
        message::set_msg_failed(context, &mut msg, "Number of retries exceeded the limit.").await?;
        context
            .sql
            .execute("DELETE FROM smtp WHERE id=?", (rowid,))
            .await
            .context("Failed to remove message with exceeded retry limit from smtp table")?;
        return Ok(());
    }
    info!(
        context,
        "Try number {retries} to send message {msg_id} (entry {rowid}) over SMTP."
    );

    let recipients_list = recipients
        .split(' ')
        .filter_map(
            |addr| match async_smtp::EmailAddress::new(addr.to_string()) {
                Ok(addr) => Some(addr),
                Err(err) => {
                    warn!(context, "Invalid recipient: {} {:?}.", addr, err);
                    None
                }
            },
        )
        .collect::<Vec<_>>();

    let status = smtp_send(context, &recipients_list, body.as_str(), smtp, Some(msg_id)).await;

    match status {
        SendResult::Retry => {}
        SendResult::Success => {
            context
                .sql
                .execute("DELETE FROM smtp WHERE id=?", (rowid,))
                .await?;
        }
        SendResult::Failure(ref err) => {
            if err.to_string().contains("Invalid unencrypted mail") {
                let res = context
                    .sql
                    .query_row_optional(
                        "SELECT chat_id, timestamp FROM msgs WHERE id=?;",
                        (msg_id,),
                        |row| Ok((row.get::<_, ChatId>(0)?, row.get::<_, i64>(1)?)),
                    )
                    .await?;

                if let Some((chat_id, timestamp_sort)) = res {
                    let addr = context.get_config(Config::ConfiguredAddr).await?;
                    let text = unencrypted_email(
                        context,
                        addr.unwrap_or_default()
                            .split('@')
                            .nth(1)
                            .unwrap_or_default(),
                    )
                    .await;
                    add_info_msg_with_cmd(
                        context,
                        chat_id,
                        &text,
                        crate::mimeparser::SystemMessage::InvalidUnencryptedMail,
                        timestamp_sort,
                        None,
                        None,
                        None,
                    )
                    .await?;
                };
            }
            context
                .sql
                .execute("DELETE FROM smtp WHERE id=?", (rowid,))
                .await?;
        }
    };

    match status {
        SendResult::Retry => Err(format_err!("Retry")),
        SendResult::Success => {
            if !context
                .sql
                .exists("SELECT COUNT(*) FROM smtp WHERE msg_id=?", (msg_id,))
                .await?
            {
                msg_id.set_delivered(context).await?;
            }
            Ok(())
        }
        SendResult::Failure(err) => Err(format_err!("{}", err)),
    }
}

/// Attempts to send queued MDNs.
async fn send_mdns(context: &Context, connection: &mut Smtp) -> Result<()> {
    loop {
        if !context.ratelimit.read().await.can_send() {
            info!(context, "Ratelimiter does not allow sending MDNs now.");
            return Ok(());
        }

        let more_mdns = send_mdn(context, connection).await?;
        if !more_mdns {
            // No more MDNs to send or one of them failed.
            return Ok(());
        }
    }
}

/// Tries to send all messages currently in `smtp`, `smtp_status_updates` and `smtp_mdns` tables.
pub(crate) async fn send_smtp_messages(context: &Context, connection: &mut Smtp) -> Result<()> {
    let ratelimited = if context.ratelimit.read().await.can_send() {
        // add status updates and sync messages to end of sending queue
        context.flush_status_updates().await?;
        context.send_sync_msg().await?;
        false
    } else {
        true
    };

    let rowids = context
        .sql
        .query_map(
            "SELECT id FROM smtp ORDER BY id ASC",
            (),
            |row| {
                let rowid: i64 = row.get(0)?;
                Ok(rowid)
            },
            |rowids| {
                rowids
                    .collect::<std::result::Result<Vec<_>, _>>()
                    .map_err(Into::into)
            },
        )
        .await?;

    info!(context, "Selected rows from SMTP queue: {rowids:?}.");
    for rowid in rowids {
        send_msg_to_smtp(context, connection, rowid)
            .await
            .context("Failed to send message")?;
    }

    // although by slow sending, ratelimit may have been expired meanwhile,
    // do not attempt to send MDNs if ratelimited happened before on status-updates/sync:
    // instead, let the caller recall this function so that more important status-updates/sync are sent out.
    if !ratelimited {
        send_mdns(context, connection)
            .await
            .context("Failed to send MDNs")?;
    }
    Ok(())
}

/// Tries to send MDN for message identified by `rfc724_mdn` to `contact_id`.
///
/// Attempts to aggregate additional MDNs for `contact_id` into sent MDN.
///
/// On failure returns an error without removing any `smtp_mdns` entries, the caller is responsible
/// for removing the corresponding entry to prevent endless loop in case the entry is invalid, e.g.
/// points to non-existent message or contact.
///
/// Returns true on success, false on temporary error.
async fn send_mdn_rfc724_mid(
    context: &Context,
    rfc724_mid: &str,
    contact_id: ContactId,
    smtp: &mut Smtp,
) -> Result<bool> {
    let contact = Contact::get_by_id(context, contact_id).await?;
    if contact.is_blocked() {
        return Err(format_err!("Contact is blocked"));
    }

    // Try to aggregate additional MDNs into this MDN.
    let additional_rfc724_mids: Vec<String> = context
        .sql
        .query_map(
            "SELECT rfc724_mid
             FROM smtp_mdns
             WHERE from_id=? AND rfc724_mid!=?",
            (contact_id, &rfc724_mid),
            |row| {
                let rfc724_mid: String = row.get(0)?;
                Ok(rfc724_mid)
            },
            |rows| rows.collect::<Result<Vec<_>, _>>().map_err(Into::into),
        )
        .await?
        .into_iter()
        .collect();

    let mimefactory = MimeFactory::from_mdn(
        context,
        contact_id,
        rfc724_mid.to_string(),
        additional_rfc724_mids.clone(),
    )
    .await?;
    let rendered_msg = mimefactory.render(context).await?;
    let body = rendered_msg.message;

    let addr = contact.get_addr();
    let recipient = async_smtp::EmailAddress::new(addr.to_string())
        .map_err(|err| format_err!("invalid recipient: {} {:?}", addr, err))?;
    let recipients = vec![recipient];

    match smtp_send(context, &recipients, &body, smtp, None).await {
        SendResult::Success => {
            info!(context, "Successfully sent MDN for {rfc724_mid}.");
            context
                .sql
                .execute("DELETE FROM smtp_mdns WHERE rfc724_mid = ?", (rfc724_mid,))
                .await?;
            if !additional_rfc724_mids.is_empty() {
                let q = format!(
                    "DELETE FROM smtp_mdns WHERE rfc724_mid IN({})",
                    sql::repeat_vars(additional_rfc724_mids.len())
                );
                context
                    .sql
                    .execute(&q, rusqlite::params_from_iter(additional_rfc724_mids))
                    .await?;
            }
            Ok(true)
        }
        SendResult::Retry => {
            info!(
                context,
                "Temporary SMTP failure while sending an MDN for {rfc724_mid}."
            );
            Ok(false)
        }
        SendResult::Failure(err) => Err(err),
    }
}

/// Tries to send a single MDN. Returns true if more MDNs should be sent.
async fn send_mdn(context: &Context, smtp: &mut Smtp) -> Result<bool> {
    let mdns_enabled = context.get_config_bool(Config::MdnsEnabled).await?;
    if !mdns_enabled {
        // User has disabled MDNs.
        context.sql.execute("DELETE FROM smtp_mdns", []).await?;
        return Ok(false);
    }
    info!(context, "Sending MDNs.");

    context
        .sql
        .execute("DELETE FROM smtp_mdns WHERE retries > 6", [])
        .await?;
    let Some(msg_row) = context
        .sql
        .query_row_optional(
            "SELECT rfc724_mid, from_id FROM smtp_mdns ORDER BY retries LIMIT 1",
            [],
            |row| {
                let rfc724_mid: String = row.get(0)?;
                let from_id: ContactId = row.get(1)?;
                Ok((rfc724_mid, from_id))
            },
        )
        .await?
    else {
        return Ok(false);
    };
    let (rfc724_mid, contact_id) = msg_row;

    context
        .sql
        .execute(
            "UPDATE smtp_mdns SET retries=retries+1 WHERE rfc724_mid=?",
            (rfc724_mid.clone(),),
        )
        .await
        .context("Failed to update MDN retries count")?;

    match send_mdn_rfc724_mid(context, &rfc724_mid, contact_id, smtp).await {
        Err(err) => {
            // If there is an error, for example there is no message corresponding to the msg_id in the
            // database, do not try to send this MDN again.
            warn!(
                context,
                "Error sending MDN for {rfc724_mid}, removing it: {err:#}."
            );
            context
                .sql
                .execute("DELETE FROM smtp_mdns WHERE rfc724_mid = ?", (rfc724_mid,))
                .await?;
            Err(err)
        }
        Ok(false) => {
            bail!("Temporary error while sending an MDN");
        }
        Ok(true) => {
            // Successfully sent MDN.
            Ok(true)
        }
    }
}