Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gleam.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name = "lumenmail"
version = "1.0.0"
version = "1.1.1"
description = "A Gleam library for sending emails via SMTP, inspired by the Rust mail-send crate"
licences = ["Apache-2.0", "MIT"]
repository = { type = "github", user = "davecaos", repo = "lumenmail" }
Expand Down
8 changes: 3 additions & 5 deletions src/lumenmail/auth.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,9 @@ pub fn encode_cram_md5(credentials: Credentials, challenge: String) -> String {
Ok(challenge_decoded) -> {
// Compute HMAC-MD5
let digest =
crypto.hmac(
<<challenge_decoded:utf8>>,
crypto.Md5,
<<password:utf8>>,
)
crypto.hmac(<<challenge_decoded:utf8>>, crypto.Md5, <<
password:utf8,
>>)
let hex_digest =
digest
|> bit_array.base16_encode()
Expand Down
37 changes: 16 additions & 21 deletions src/lumenmail/message.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,7 @@ fn build_message_string(message: Message, from_addr: Address) -> String {
// Text only, no attachments
Some(text), None, True ->
builder
|> string_tree.append(
"Content-Type: text/plain; charset=utf-8\r\n\r\n",
)
|> string_tree.append("Content-Type: text/plain; charset=utf-8\r\n\r\n")
|> string_tree.append(text)

// HTML only, no attachments
Expand All @@ -416,9 +414,7 @@ fn build_message_string(message: Message, from_addr: Address) -> String {
<> "\"\r\n\r\n",
)
|> string_tree.append("--" <> boundary <> "\r\n")
|> string_tree.append(
"Content-Type: text/plain; charset=utf-8\r\n\r\n",
)
|> string_tree.append("Content-Type: text/plain; charset=utf-8\r\n\r\n")
|> string_tree.append(text <> "\r\n\r\n")
|> string_tree.append("--" <> boundary <> "\r\n")
|> string_tree.append("Content-Type: text/html; charset=utf-8\r\n\r\n")
Expand Down Expand Up @@ -491,11 +487,7 @@ fn build_message_string(message: Message, from_addr: Address) -> String {
builder
|> string_tree.append("--" <> mixed_boundary <> "\r\n")
|> string_tree.append(
"Content-Type: "
<> ct
<> "; name=\""
<> att.filename
<> "\"\r\n",
"Content-Type: " <> ct <> "; name=\"" <> att.filename <> "\"\r\n",
)
|> string_tree.append("Content-Transfer-Encoding: base64\r\n")
|> string_tree.append(
Expand All @@ -505,14 +497,14 @@ fn build_message_string(message: Message, from_addr: Address) -> String {
<> att.filename
<> "\"\r\n",
)
|> string_tree.append(case att.content_id {
Some(cid) -> "Content-ID: <" <> cid <> ">\r\n"
None -> ""
})
|> string_tree.append("\r\n")
|> string_tree.append(
case att.content_id {
Some(cid) -> "Content-ID: <" <> cid <> ">\r\n"
None -> ""
},
bit_array.base64_encode(att.data, True) <> "\r\n\r\n",
)
|> string_tree.append("\r\n")
|> string_tree.append(bit_array.base64_encode(att.data, True) <> "\r\n\r\n")
})

b
Expand All @@ -522,10 +514,13 @@ fn build_message_string(message: Message, from_addr: Address) -> String {
// No body at all
None, None, True ->
builder
|> string_tree.append(
"Content-Type: text/plain; charset=utf-8\r\n\r\n",
)
|> string_tree.append("Content-Type: text/plain; charset=utf-8\r\n\r\n")
}

string_tree.to_string(builder)
let result = string_tree.to_string(builder)
// Ensure message ends with \r\n so SMTP termination sequence (\r\n.\r\n) works
case string.ends_with(result, "\r\n") {
True -> result
False -> result <> "\r\n"
}
}
9 changes: 3 additions & 6 deletions src/lumenmail/network.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ pub type TcpOption {
// =============================================================================

/// Establishes a TCP connection to the SMTP server.
pub fn tcp_connect(
host: String,
port: Int,
timeout: Int,
) -> SmtpResult(Socket) {
pub fn tcp_connect(host: String, port: Int, timeout: Int) -> SmtpResult(Socket) {
let options = [Binary, ActiveFalse, PacketLine, ReuseAddr]
case do_tcp_connect(host, port, options, timeout) {
Ok(socket) -> Ok(socket)
Expand Down Expand Up @@ -224,7 +220,8 @@ fn parse_response_line(line: String) -> SmtpResult(SmtpResponse) {
3 -> Ok(SmtpResponse(code, "", False))
_ -> {
let separator = string.slice(clean_line, 3, 1)
let message = string.slice(clean_line, 4, string.length(clean_line) - 4)
let message =
string.slice(clean_line, 4, string.length(clean_line) - 4)
let is_multiline = separator == "-"
Ok(SmtpResponse(code, message, is_multiline))
}
Expand Down
139 changes: 60 additions & 79 deletions src/lumenmail/smtp.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ pub type SmtpClientBuilder {

/// Active SMTP connection.
pub type SmtpClient {
SmtpClient(socket: network.Socket, capabilities: ServerCapabilities, is_tls: Bool)
SmtpClient(
socket: network.Socket,
capabilities: ServerCapabilities,
is_tls: Bool,
)
}

/// Socket type - re-exported from network module.
Expand Down Expand Up @@ -145,45 +149,43 @@ pub fn connect(builder: SmtpClientBuilder) -> SmtpResult(SmtpClient) {
))

// Upgrade to TLS via STARTTLS if needed
use #(socket, is_tls, capabilities) <- result.try(case
builder.tls_mode,
is_tls,
capabilities.starttls
{
StartTls, False, True -> {
// Send STARTTLS command
use _ <- result.try(send_command(
socket,
is_tls,
"STARTTLS",
builder.timeout_ms,
))
use response <- result.try(read_response(
socket,
is_tls,
builder.timeout_ms,
))
use _ <- result.try(check_response_code(response, 220))
use #(socket, is_tls, capabilities) <- result.try(
case builder.tls_mode, is_tls, capabilities.starttls {
StartTls, False, True -> {
// Send STARTTLS command
use _ <- result.try(send_command(
socket,
is_tls,
"STARTTLS",
builder.timeout_ms,
))
use response <- result.try(read_response(
socket,
is_tls,
builder.timeout_ms,
))
use _ <- result.try(check_response_code(response, 220))

// Upgrade to TLS
use tls_socket <- result.try(ssl_connect(
socket,
builder.host,
builder.allow_invalid_certs,
builder.timeout_ms,
))
// Upgrade to TLS
use tls_socket <- result.try(ssl_connect(
socket,
builder.host,
builder.allow_invalid_certs,
builder.timeout_ms,
))

// Re-send EHLO after TLS upgrade
use new_caps <- result.try(send_ehlo(
tls_socket,
True,
builder.helo_host,
builder.timeout_ms,
))
Ok(#(tls_socket, True, new_caps))
}
_, _, _ -> Ok(#(socket, is_tls, capabilities))
})
// Re-send EHLO after TLS upgrade
use new_caps <- result.try(send_ehlo(
tls_socket,
True,
builder.helo_host,
builder.timeout_ms,
))
Ok(#(tls_socket, True, new_caps))
}
_, _, _ -> Ok(#(socket, is_tls, capabilities))
},
)

// Authenticate if credentials provided
use _ <- result.try(case builder.credentials {
Expand Down Expand Up @@ -246,12 +248,7 @@ pub fn send(client: SmtpClient, msg: Message) -> SmtpResult(Nil) {
)

// DATA
use _ <- result.try(send_command(
client.socket,
client.is_tls,
"DATA",
30_000,
))
use _ <- result.try(send_command(client.socket, client.is_tls, "DATA", 30_000))
use response <- result.try(read_response(client.socket, client.is_tls, 30_000))
use _ <- result.try(check_response_code(response, 354))

Expand Down Expand Up @@ -307,12 +304,7 @@ pub fn send_raw(
)

// DATA
use _ <- result.try(send_command(
client.socket,
client.is_tls,
"DATA",
30_000,
))
use _ <- result.try(send_command(client.socket, client.is_tls, "DATA", 30_000))
use response <- result.try(read_response(client.socket, client.is_tls, 30_000))
use _ <- result.try(check_response_code(response, 354))

Expand Down Expand Up @@ -341,24 +333,14 @@ pub fn close(client: SmtpClient) -> SmtpResult(Nil) {

/// Resets the connection state (for sending multiple emails).
pub fn reset(client: SmtpClient) -> SmtpResult(Nil) {
use _ <- result.try(send_command(
client.socket,
client.is_tls,
"RSET",
30_000,
))
use _ <- result.try(send_command(client.socket, client.is_tls, "RSET", 30_000))
use response <- result.try(read_response(client.socket, client.is_tls, 30_000))
check_response_code(response, 250)
}

/// Sends a NOOP command to keep connection alive.
pub fn noop(client: SmtpClient) -> SmtpResult(Nil) {
use _ <- result.try(send_command(
client.socket,
client.is_tls,
"NOOP",
30_000,
))
use _ <- result.try(send_command(client.socket, client.is_tls, "NOOP", 30_000))
use response <- result.try(read_response(client.socket, client.is_tls, 30_000))
check_response_code(response, 250)
}
Expand Down Expand Up @@ -386,25 +368,24 @@ fn send_ehlo(

case response.code >= 200 && response.code < 300 {
True -> Ok(parse_capabilities(response.message))
False ->
False -> {
// Fallback to HELO
{
use _ <- result.try(send_command(
socket,
is_tls,
"HELO " <> helo_host,
timeout,
))
use response <- result.try(read_response(socket, is_tls, timeout))
case response.code >= 200 && response.code < 300 {
True -> Ok(types.empty_capabilities())
False ->
Error(CommandRejected(
response.code,
"HELO failed: " <> response.message,
))
}
use _ <- result.try(send_command(
socket,
is_tls,
"HELO " <> helo_host,
timeout,
))
use response <- result.try(read_response(socket, is_tls, timeout))
case response.code >= 200 && response.code < 300 {
True -> Ok(types.empty_capabilities())
False ->
Error(CommandRejected(
response.code,
"HELO failed: " <> response.message,
))
}
}
}
}

Expand Down
40 changes: 13 additions & 27 deletions test/gmail_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ pub fn main() {
io.println("===========================================")
io.println("")
io.println("Configuration:")
io.println(" SMTP Server: " <> smtp_server <> ":" <> int.to_string(smtp_port))
io.println(
" SMTP Server: " <> smtp_server <> ":" <> int.to_string(smtp_port),
)
io.println(" Sender: " <> sender_email)
io.println(" Recipient: " <> test_recipient)
io.println("")
Expand All @@ -80,29 +82,20 @@ pub fn main() {
|> message.from_name_email(sender_name, sender_email)
|> message.to_email(test_recipient)
|> message.subject("Test Email from LumenMail Library")
|> message.text_body(
"Hello!
|> message.text_body("Hello!

This is a test email sent using the Gleam LumenMail library.

If you received this email, the SMTP relay is working correctly!

Configuration used:
- SMTP Server: "
<> smtp_server
<> "
- Port: "
<> int.to_string(smtp_port)
<> " (STARTTLS)
- Sender: "
<> sender_email
<> "
- SMTP Server: " <> smtp_server <> "
- Port: " <> int.to_string(smtp_port) <> " (STARTTLS)
- Sender: " <> sender_email <> "

Best regards,
LumenMail Test Script",
)
|> message.html_body(
"<!DOCTYPE html>
LumenMail Test Script")
|> message.html_body("<!DOCTYPE html>
<html>
<head>
<style>
Expand Down Expand Up @@ -130,15 +123,9 @@ LumenMail Test Script",
<div class=\"config\">
<h3>Configuration Used:</h3>
<ul>
<li><strong>SMTP Server:</strong> "
<> smtp_server
<> "</li>
<li><strong>Port:</strong> "
<> int.to_string(smtp_port)
<> " (STARTTLS)</li>
<li><strong>Sender:</strong> "
<> sender_email
<> "</li>
<li><strong>SMTP Server:</strong> " <> smtp_server <> "</li>
<li><strong>Port:</strong> " <> int.to_string(smtp_port) <> " (STARTTLS)</li>
<li><strong>Sender:</strong> " <> sender_email <> "</li>
</ul>
</div>
</div>
Expand All @@ -147,8 +134,7 @@ LumenMail Test Script",
</div>
</div>
</body>
</html>",
)
</html>")

io.println("Connecting to SMTP server...")

Expand Down
Loading