1
/*
2
 * This file is part of mailpot
3
 *
4
 * Copyright 2020 - Manos Pitsidianakis
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 */
19

            
20
//! Submit e-mail through SMTP.
21

            
22
use std::{future::Future, pin::Pin};
23

            
24
use melib::smtp::*;
25

            
26
use crate::{errors::*, queue::QueueEntry, Connection};
27

            
28
type ResultFuture<T> = Result<Pin<Box<dyn Future<Output = Result<T>> + Send + 'static>>>;
29

            
30
impl Connection {
31
    /// Return an SMTP connection handle if the database connection has one
32
    /// configured.
33
6
    pub fn new_smtp_connection(&self) -> ResultFuture<SmtpConnection> {
34
6
        if let crate::SendMail::Smtp(ref smtp_conf) = &self.conf().send_mail {
35
6
            let smtp_conf = smtp_conf.clone();
36
18
            Ok(Box::pin(async move {
37
12
                Ok(SmtpConnection::new_connection(smtp_conf).await?)
38
6
            }))
39
        } else {
40
            Err("No SMTP configuration found: use the shell command instead.".into())
41
        }
42
6
    }
43

            
44
    /// Submit queue items from `values` to their recipients.
45
8
    pub async fn submit(
46
5
        smtp_connection: &mut melib::smtp::SmtpConnection,
47
5
        message: &QueueEntry,
48
5
        dry_run: bool,
49
33
    ) -> Result<()> {
50
        let QueueEntry {
51
5
            ref comment,
52
5
            ref to_addresses,
53
5
            ref from_address,
54
5
            ref subject,
55
5
            ref message,
56
            ..
57
        } = message;
58
5
        log::info!(
59
            "Sending message from {from_address} to {to_addresses} with subject {subject:?} and \
60
             comment {comment:?}",
61
        );
62
10
        let recipients = melib::Address::list_try_from(to_addresses)
63
5
            .context(format!("Could not parse {to_addresses:?}"))?;
64
5
        if dry_run {
65
            log::warn!("Dry run is true, not actually submitting anything to SMTP server.");
66
        } else {
67
20
            smtp_connection
68
5
                .mail_transaction(&String::from_utf8_lossy(message), Some(&recipients))
69
30
                .await?;
70
        }
71
5
        Ok(())
72
21
    }
73
}