diff --git a/src/mailer.rs b/src/mailer.rs index ecaa016..af74aa2 100644 --- a/src/mailer.rs +++ b/src/mailer.rs @@ -20,7 +20,7 @@ pub struct Mailer { impl Mailer { /// Tries to initialize the mailer. - pub fn build(config: &Config) -> Result { + pub async fn build(config: &Config) -> Result { // Mail server credentials for login. let credentials = Credentials::new( config.email_server.email.clone(), @@ -32,6 +32,10 @@ impl Mailer { .context("Failed to connect to the email server!")? .credentials(credentials) .build(); + mailer + .test_connection() + .await + .context("Email connection test failed!")?; // Set the From and To mailboxes for every sent mail. let message_builder = Message::builder() diff --git a/src/main.rs b/src/main.rs index 06f1766..17e6699 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,27 +16,29 @@ use axum::{ }; use std::{future::ready, net::SocketAddr, process}; use tower_http::services::ServeDir; -use tracing::info; +use tracing::{error, info}; -use crate::states::AppState; +use crate::{config::Config, states::AppState}; -async fn init() -> Result<()> { - let app_state = AppState::build()?; +async fn init(logger_initialized: &mut bool) -> Result<()> { + let config = Config::build()?; + + logging::init_logger( + &config.log_file, + config.utc_offset.hours, + config.utc_offset.minutes, + )?; + *logger_initialized = true; // The path prefix of all routes. - let path_prefix = app_state.config.path_prefix.clone(); + let path_prefix = config.path_prefix.clone(); - let socket_address = app_state - .config + let socket_address = config .socket_address .parse::() .context("Failed to parse the socket address: {e:?}")?; - logging::init_logger( - &app_state.config.log_file, - app_state.config.utc_offset.hours, - app_state.config.utc_offset.minutes, - )?; + let app_state = AppState::build(config).await?; // The service for serving the static files. let static_service = @@ -60,8 +62,14 @@ async fn init() -> Result<()> { /// Single thread. #[tokio::main(flavor = "current_thread")] async fn main() { - if let Err(e) = init().await { - eprintln!("{e:?}"); + let mut logger_initialized = false; + + if let Err(e) = init(&mut logger_initialized).await { + if logger_initialized { + error!("{e:?}"); + } else { + eprintln!("{e:?}"); + } process::exit(1); }; } diff --git a/src/states.rs b/src/states.rs index 330f935..da546cd 100644 --- a/src/states.rs +++ b/src/states.rs @@ -14,9 +14,8 @@ pub struct AppState { impl AppState { /// Try to build the app state. - pub fn build() -> Result { - let config = Config::build()?; - let mailer = Arc::new(Mailer::build(&config)?); + pub async fn build(config: Config) -> Result { + let mailer = Arc::new(Mailer::build(&config).await?); let config = Arc::new(config); // Mutex for write access.