newsletter

This commit is contained in:
Alexander Heldt
2025-11-08 20:40:41 +01:00
parent 760f5ef4a6
commit 589a3b886a
10 changed files with 370 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
import gleam/string
import simplifile
pub fn read_emails(path: String) -> Result(List(String), Nil) {
case simplifile.read(path) {
Error(_) -> Error(Nil)
Ok(content) ->
string.trim(content)
|> string.split("\n")
|> Ok
}
}
pub fn create_log_file(path: String) -> Result(Nil, Nil) {
case simplifile.create_file(path) {
Error(_) -> Error(Nil)
Ok(_) -> Ok(Nil)
}
}
pub fn log_sent_email(path: String, email: String) -> Result(Nil, Nil) {
case simplifile.append(path, email <> "\n") {
Error(_) -> Error(Nil)
Ok(_) -> Ok(Nil)
}
}
pub fn send_newsletter(
emails_path: String,
log_path: String,
send_email: fn(String) -> Result(Nil, Nil),
) -> Result(Nil, Nil) {
case create_log_file(log_path), read_emails(emails_path) {
Ok(_), Ok(emails) -> send_emails_and_log(emails, send_email, log_path)
_, _ -> Error(Nil)
}
}
fn send_emails_and_log(
emails: List(String),
send_fn: fn(String) -> Result(Nil, Nil),
log_path: String,
) -> Result(Nil, Nil) {
let _ = case emails {
[] -> Ok(Nil)
[email, ..rest] -> {
let _ = case send_fn(email) {
Error(_) -> Error(Nil)
Ok(_) -> log_sent_email(log_path, email)
}
send_emails_and_log(rest, send_fn, log_path)
}
}
}
// It should read all the email addresses from the given file and attempt to send an email to every one of them. If the anonymous function that sends the email returns an `Ok` value, write the email address to the log file. Make sure to do it as soon as the email is sent.