Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

fix(email): route SMTP sends through the configured proxy (#13984)

Harshvardhan Bahukhandi23a744fb98f5
diff --git a/Cargo.lock b/Cargo.lock
index a34d001ffa..330ea36116 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3606,6 +3606,7 @@ dependencies = [
"thiserror 1.0.69",
"time 0.3.41",
"tokio 1.48.0",
+ "tokio-socks",
"tokio-stream",
"tonic 0.14.5",
"tonic-prost",
@@ -5591,11 +5592,13 @@ version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87ffd14fa289730e3ad68edefdc31f603d56fe716ec38f2076bb7410e09147c2"
dependencies = [
+ "async-trait",
"base64 0.22.1",
"chumsky",
"email-encoding",
"email_address",
"fastrand",
+ "futures-io",
"futures-util",
"hostname",
"httpdate",
@@ -5607,6 +5610,7 @@ dependencies = [
"quoted_printable",
"socket2 0.5.10",
"tokio 1.48.0",
+ "tokio-native-tls",
"url 2.5.4",
]
@@ -7253,7 +7257,7 @@ dependencies = [
"regex-cache",
"serde",
"serde_derive",
- "strum 0.25.0",
+ "strum 0.26.3",
"thiserror 1.0.69",
]
@@ -10877,6 +10881,18 @@ dependencies = [
"tokio 1.48.0",
]
+[[package]]
+name = "tokio-socks"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7e2948f60dbe26b35f2c7fb74ac2854c1fddded0fe9d7548fcc674a246f7615"
+dependencies = [
+ "either",
+ "futures-util",
+ "thiserror 1.0.69",
+ "tokio 1.48.0",
+]
+
[[package]]
name = "tokio-stream"
version = "0.1.17"
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 5014f24260..a454c5638e 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -82,15 +82,29 @@ wildcard_origin = false # If true, allows any origin to make req
sender_email = "[email protected]" # Sender email
aws_region = "" # AWS region used by AWS SES
allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email
-active_email_client = "SES" # The currently active email client
+active_email_client = "SES" # The currently active email client (NO_EMAIL_CLIENT | SES | SMTP)
recon_recipient_email = "[email protected]" # Recipient email for recon request email
prod_intent_recipient_email = "[email protected]" # Recipient email for prod intent email
-# Configuration for aws ses, applicable when the active email client is SES
+# Required only if `active_email_client` above is set to "SES"
[email.aws_ses]
email_role_arn = "" # The amazon resource name ( arn ) of the role which has permission to send emails
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
+# Required only if `active_email_client` above is set to "SMTP"
+[email.smtp]
+host = "mailhog" # SMTP host
+port = 1025 # SMTP port
+timeout = 10 # Timeout for SMTP connection in seconds
+connection = "plaintext" # currently plaintext and starttls are supported
+
+# Optional, only if [email.smtp] above needs to be reached through a SOCKS5 proxy
+[email.smtp.socks5]
+host = "127.0.0.1" # SOCKS5 proxy hostname or IP
+port = 1080 # SOCKS5 proxy port
+username = "testuser" # SOCKS5 username, if the proxy requires auth
+password = "testpass" # SOCKS5 password, if the proxy requires auth
+
[events]
source = "logs" # The event sink to push events supports kafka or logs (stdout)
emit_external_service_call_events = false # Enable external service call event emission
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index a5e1232845..a750e35abf 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -70,7 +70,7 @@ error-stack = "0.4.1"
hex = "0.4.3"
hyper = "0.14.32"
hyper-proxy = "0.9.1"
-lettre = "0.11.16"
+lettre = { version = "0.11.16", features = ["tokio1", "tokio1-native-tls"] }
once_cell = "1.21.3"
serde = { version = "1.0.219", features = ["derive"] }
thiserror = "1.0.69"
@@ -81,7 +81,8 @@ prost = { version = "0.14", optional = true }
prost-reflect = { version = "0.16.5", features = ["serde"], optional = true }
prost-types = { version = "0.14", optional = true }
time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] }
-tokio = "1.48.0"
+tokio = { version = "1.48.0", features = ["net", "io-util", "time", "sync"] }
+tokio-socks = "0.5"
tonic = "0.14"
tonic-prost = { version = "0.14", optional = true }
tonic-reflection = "0.14.0"
diff --git a/crates/external_services/src/email/smtp.rs b/crates/external_services/src/email/smtp.rs
index 4eea8d5d9e..bcab183d76 100644
--- a/crates/external_services/src/email/smtp.rs
+++ b/crates/external_services/src/email/smtp.rs
@@ -7,12 +7,90 @@ use lettre::{
address::AddressError,
error,
message::{header::ContentType, Mailbox},
- transport::smtp::{self, authentication::Credentials},
- Message, SmtpTransport, Transport,
+ transport::smtp::{
+ self,
+ authentication::{Credentials, Mechanism},
+ client::{AsyncSmtpConnection, AsyncTokioStream, TlsParameters},
+ extension::ClientId,
+ },
+ Message,
};
+use router_env::logger;
+use tokio::net::TcpStream;
+use tokio_socks::tcp::Socks5Stream;
use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
+async fn connect_direct(host: &str, port: u16) -> Result<TcpStream, SmtpError> {
+ TcpStream::connect((host, port))
+ .await
+ .map_err(SmtpError::DirectConnectionFailed)
+}
+
+/// SOCKS5 proxy to tunnel the SMTP connection through (absent means connect directly); username/password auth (RFC 1929) is sent to the proxy in cleartext.
+#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Socks5Config {
+ /// SOCKS5 proxy hostname or IP.
+ pub host: String,
+ /// SOCKS5 proxy port.
+ pub port: u16,
+ /// SOCKS5 username, if the proxy requires auth.
+ pub username: Option<Secret<String>>,
+ /// SOCKS5 password, if the proxy requires auth.
+ pub password: Option<Secret<String>>,
+}
+
+async fn connect_via_socks5(
+ socks5: &Socks5Config,
+ smtp_host: &str,
+ smtp_port: u16,
+) -> Result<TcpStream, SmtpError> {
+ let proxy_addrs = tokio::net::lookup_host((socks5.host.as_str(), socks5.port))
+ .await
+ .map_err(SmtpError::Socks5ProxyResolutionFailed)?
+ .collect::<Vec<_>>();
+
+ let target = (smtp_host, smtp_port);
+
+ // Try every resolved address, not just the first (matches connect_direct's retry).
+ let mut last_error = SmtpError::Socks5ProxyResolutionFailed(std::io::Error::new(
+ std::io::ErrorKind::NotFound,
+ "proxy hostname resolved to no addresses",
+ ));
+
+ for proxy_addr in proxy_addrs {
+ let result = match socks5.username.as_ref().zip(socks5.password.as_ref()) {
+ Some((username, password)) => {
+ Socks5Stream::connect_with_password(
+ proxy_addr,
+ target,
+ username.peek().as_str(),
+ password.peek().as_str(),
+ )
+ .await
+ }
+ None => Socks5Stream::connect(proxy_addr, target).await,
+ };
+
+ match result {
+ Ok(stream) => return Ok(stream.into_inner()),
+ Err(error) => {
+ logger::warn!(
+ ?error,
+ proxy_host = %socks5.host,
+ proxy_port = socks5.port,
+ %proxy_addr,
+ "SOCKS5 connection attempt failed, trying next resolved address if any"
+ );
+ last_error = SmtpError::Socks5ConnectionFailed(error);
+ }
+ }
+ }
+
+ Err(last_error)
+}
+
/// Client for SMTP server operation
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SmtpServer {
@@ -23,45 +101,45 @@ pub struct SmtpServer {
}
impl SmtpServer {
- /// A helper function to create SMTP server client
- pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> {
- let host = self.smtp_config.host.clone();
+ pub(crate) async fn create_client(&self) -> CustomResult<AsyncSmtpConnection, SmtpError> {
+ let host = &self.smtp_config.host;
let port = self.smtp_config.port;
- let timeout = Some(Duration::from_secs(self.smtp_config.timeout));
- let credentials = self
- .smtp_config
- .username
- .clone()
- .zip(self.smtp_config.password.clone())
- .map(|(username, password)| {
- Credentials::new(username.peek().to_owned(), password.peek().to_owned())
- });
- match &self.smtp_config.connection {
- SmtpConnection::StartTls => match credentials {
- Some(credentials) => Ok(SmtpTransport::starttls_relay(&host)
- .map_err(SmtpError::ConnectionFailure)?
- .port(port)
- .timeout(timeout)
- .credentials(credentials)
- .build()),
- None => Ok(SmtpTransport::starttls_relay(&host)
- .map_err(SmtpError::ConnectionFailure)?
- .port(port)
- .timeout(timeout)
- .build()),
- },
- SmtpConnection::Plaintext => match credentials {
- Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host)
- .port(port)
- .timeout(timeout)
- .credentials(credentials)
- .build()),
- None => Ok(SmtpTransport::builder_dangerous(&host)
- .port(port)
- .timeout(timeout)
- .build()),
- },
+ let client_id = ClientId::default();
+ let timeout = Duration::from_secs(self.smtp_config.timeout);
+
+ let stream = tokio::time::timeout(timeout, async {
+ match self.smtp_config.socks5.as_ref() {
+ Some(socks5) => connect_via_socks5(socks5, host, port).await,
+ None => connect_direct(host, port).await,
+ }
+ })
+ .await
+ .change_context(SmtpError::Timeout)
+ .attach_printable("Timed out establishing the underlying connection to the SMTP host")??;
+
+ let stream: Box<dyn AsyncTokioStream> = Box::new(stream);
+
+ let mut conn = tokio::time::timeout(
+ timeout,
+ AsyncSmtpConnection::connect_with_transport(stream, &client_id),
+ )
+ .await
+ .change_context(SmtpError::Timeout)
+ .attach_printable("Timed out completing the SMTP connect handshake")?
+ .map_err(SmtpError::ConnectionFailure)?;
+
+ if matches!(self.smtp_config.connection, SmtpConnection::StartTls) {
+ let tls_parameters = TlsParameters::builder(host.clone())
+ .build()
+ .map_err(SmtpError::ConnectionFailure)?;
+ tokio::time::timeout(timeout, conn.starttls(tls_parameters, &client_id))
+ .await
+ .change_context(SmtpError::Timeout)
+ .attach_printable("Timed out during the STARTTLS upgrade")?
+ .map_err(SmtpError::ConnectionFailure)?;
}
+
+ Ok(conn)
}
/// Constructs a new SMTP client
pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self {
@@ -70,7 +148,6 @@ impl SmtpServer {
smtp_config: smtp_config.clone(),
}
}
- /// helper function to convert email id into Mailbox
fn to_mail_box(email: String) -> EmailResult<Mailbox> {
Ok(Mailbox::new(
None,
@@ -98,6 +175,8 @@ pub struct SmtpServerConfig {
/// Connection type of the SMTP server
#[serde(default)]
pub connection: SmtpConnection,
+ /// SOCKS5 proxy config; absent means connect directly.
+ pub socks5: Option<Socks5Config>,
}
/// Enum that contains the connection types of the SMTP server
@@ -129,7 +208,31 @@ impl SmtpServerConfig {
})
},
)?;
- Ok(())
+ self.socks5.as_ref().map_or(Ok(()), Socks5Config::validate)
+ }
+}
+
+impl Socks5Config {
+ fn validate(&self) -> Result<(), &'static str> {
+ use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+ when(self.host.is_default_or_empty(), || {
+ Err("email.smtp.socks5.host must not be empty")
+ })?;
+ when(self.port == 0, || {
+ Err("email.smtp.socks5.port must not be zero")
+ })?;
+ match (self.username.as_ref(), self.password.as_ref()) {
+ (Some(username), Some(password)) => {
+ when(username.peek().is_default_or_empty(), || {
+ Err("email.smtp.socks5.username must not be empty")
+ })?;
+ when(password.peek().is_default_or_empty(), || {
+ Err("email.smtp.socks5.password must not be empty")
+ })
+ }
+ (None, None) => Ok(()),
+ _ => Err("email.smtp.socks5 username and password must both be set, or neither"),
+ }
}
}
@@ -148,12 +251,9 @@ impl EmailClient for SmtpServer {
recipient: pii::Email,
subject: String,
body: Self::RichText,
+ // Unused here — SES uses this; SMTP's proxy lives in smtp_config.socks5.
_proxy_url: Option<&String>,
) -> EmailResult<()> {
- // Create a client every time when the email is being sent
- let email_client =
- Self::create_client(self).change_context(EmailError::EmailSendingFailure)?;
-
let email = Message::builder()
.to(Self::to_mail_box(recipient.peek().to_string())?)
.from(Self::to_mail_box(self.sender.peek().to_string())?)
@@ -163,27 +263,86 @@ impl EmailClient for SmtpServer {
.map_err(SmtpError::MessageBuildingFailed)
.change_context(EmailError::EmailSendingFailure)?;
- email_client
- .send(&email)
+ let mut conn = self
+ .create_client()
+ .await
+ .change_context(EmailError::EmailSendingFailure)?;
+
+ let timeout = Duration::from_secs(self.smtp_config.timeout);
+
+ let credentials = self
+ .smtp_config
+ .username
+ .clone()
+ .zip(self.smtp_config.password.clone())
+ .map(|(username, password)| {
+ Credentials::new(username.peek().to_owned(), password.peek().to_owned())
+ });
+
+ if let Some(credentials) = credentials {
+ tokio::time::timeout(
+ timeout,
+ conn.auth(&[Mechanism::Plain, Mechanism::Login], &credentials),
+ )
+ .await
+ .change_context(SmtpError::Timeout)
+ .attach_printable("SMTP AUTH command timed out")
+ .change_context(EmailError::EmailSendingFailure)?
+ .map_err(SmtpError::AuthenticationFailure)
+ .change_context(EmailError::EmailSendingFailure)?;
+ }
+
+ tokio::time::timeout(timeout, conn.send(email.envelope(), &email.formatted()))
+ .await
+ .change_context(SmtpError::Timeout)
+ .attach_printable("SMTP SEND command timed out")
+ .change_context(EmailError::EmailSendingFailure)?
.map_err(SmtpError::SendingFailure)
.change_context(EmailError::EmailSendingFailure)?;
+
+ match tokio::time::timeout(timeout, conn.quit()).await {
+ Ok(Ok(_)) => {}
+ Ok(Err(error)) => {
+ logger::warn!(?error, "SMTP QUIT failed after message was already sent");
+ }
+ Err(_) => {
+ logger::warn!("SMTP QUIT timed out after message was already sent");
+ }
+ }
+
Ok(())
}
}
-/// Errors that could occur during SES operations.
+/// Errors that could occur during SMTP operations.
#[derive(Debug, thiserror::Error)]
pub enum SmtpError {
- /// An error occurred in the SMTP while sending email.
+ /// An error occurred in the SMTP client while sending the email (the SMTP `MAIL
+ /// FROM`/`RCPT TO`/`DATA` exchange).
#[error("Failed to Send Email {0:?}")]
SendingFailure(smtp::Error),
- /// An error occurred in the SMTP while building the message content.
+ /// SMTP authentication (AUTH command) failed.
+ #[error("SMTP authentication failed: {0:?}")]
+ AuthenticationFailure(smtp::Error),
+ /// The SMTP connect handshake or STARTTLS upgrade failed.
#[error("Failed to create connection {0:?}")]
ConnectionFailure(smtp::Error),
- /// An error occurred in the SMTP while building the message content.
+ /// The outgoing email's message content (headers/body) could not be built.
#[error("Failed to Build Email content {0:?}")]
MessageBuildingFailed(error::Error),
- /// An error occurred in the SMTP while building the message content.
+ /// The sender or recipient email address could not be parsed.
#[error("Failed to parse given email {0:?}")]
EmailParsingFailed(AddressError),
+ /// The configured SOCKS5 proxy hostname could not be resolved.
+ #[error("Failed to resolve SOCKS5 proxy address: {0:?}")]
+ Socks5ProxyResolutionFailed(std::io::Error),
+ /// Establishing the SOCKS5 tunnel failed (proxy unreachable, auth rejected, or protocol error).
+ #[error("SOCKS5 proxy connection failed: {0}")]
+ Socks5ConnectionFailed(tokio_socks::Error),
+ /// TCP connection to the SMTP host itself failed (non-proxied direct connect).
+ #[error("Failed to connect to SMTP server: {0:?}")]
+ DirectConnectionFailed(std::io::Error),
+ /// A network step exceeded `smtp_config.timeout`.
+ #[error("SMTP operation timed out")]
+ Timeout,
}