Unsubscribe link in emails sent
This commit is contained in:
@@ -44,13 +44,14 @@ pub async fn try_execute_task(
|
||||
if task.is_none() {
|
||||
return Ok(ExecutionOutcome::EmptyQueue);
|
||||
}
|
||||
let (transaction, issue_id, email) = task.unwrap();
|
||||
let (transaction, task) = task.unwrap();
|
||||
Span::current()
|
||||
.record("newsletter_issue_id", display(issue_id))
|
||||
.record("subscriber_email", display(&email));
|
||||
match SubscriberEmail::parse(email.clone()) {
|
||||
.record("newsletter_issue_id", display(task.newsletter_issue_id))
|
||||
.record("subscriber_email", display(&task.subscriber_email));
|
||||
match SubscriberEmail::parse(task.subscriber_email.clone()) {
|
||||
Ok(email) => {
|
||||
let issue = get_issue(connection_pool, issue_id).await?;
|
||||
let mut issue = get_issue(connection_pool, task.newsletter_issue_id).await?;
|
||||
issue.inject_unsubscribe_token(&task.unsubscribe_token);
|
||||
if let Err(e) = email_client
|
||||
.send_email(
|
||||
&email,
|
||||
@@ -73,7 +74,12 @@ pub async fn try_execute_task(
|
||||
);
|
||||
}
|
||||
}
|
||||
delete_task(transaction, issue_id, &email).await?;
|
||||
delete_task(
|
||||
transaction,
|
||||
task.newsletter_issue_id,
|
||||
&task.subscriber_email,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(ExecutionOutcome::TaskCompleted)
|
||||
}
|
||||
@@ -84,6 +90,13 @@ struct NewsletterIssue {
|
||||
html_content: String,
|
||||
}
|
||||
|
||||
impl NewsletterIssue {
|
||||
fn inject_unsubscribe_token(&mut self, token: &str) {
|
||||
self.text_content = self.text_content.replace("UNSUBSCRIBE_TOKEN", token);
|
||||
self.html_content = self.html_content.replace("UNSUBSCRIBE_TOKEN", token);
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
async fn get_issue(
|
||||
connection_pool: &PgPool,
|
||||
@@ -103,14 +116,20 @@ async fn get_issue(
|
||||
Ok(issue)
|
||||
}
|
||||
|
||||
pub struct Task {
|
||||
pub newsletter_issue_id: Uuid,
|
||||
pub subscriber_email: String,
|
||||
pub unsubscribe_token: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
async fn dequeue_task(
|
||||
connection_pool: &PgPool,
|
||||
) -> Result<Option<(Transaction<'static, Postgres>, Uuid, String)>, anyhow::Error> {
|
||||
) -> Result<Option<(Transaction<'static, Postgres>, Task)>, anyhow::Error> {
|
||||
let mut transaction = connection_pool.begin().await?;
|
||||
let query = sqlx::query!(
|
||||
r#"
|
||||
SELECT newsletter_issue_id, subscriber_email
|
||||
SELECT newsletter_issue_id, subscriber_email, unsubscribe_token
|
||||
FROM issue_delivery_queue
|
||||
FOR UPDATE
|
||||
SKIP LOCKED
|
||||
@@ -119,11 +138,12 @@ async fn dequeue_task(
|
||||
);
|
||||
let r = transaction.fetch_optional(query).await?;
|
||||
if let Some(row) = r {
|
||||
Ok(Some((
|
||||
transaction,
|
||||
row.get("newsletter_issue_id"),
|
||||
row.get("subscriber_email"),
|
||||
)))
|
||||
let task = Task {
|
||||
newsletter_issue_id: row.get("newsletter_issue_id"),
|
||||
subscriber_email: row.get("subscriber_email"),
|
||||
unsubscribe_token: row.get("unsubscribe_token"),
|
||||
};
|
||||
Ok(Some((transaction, task)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{
|
||||
idempotency::{IdempotencyKey, save_response, try_processing},
|
||||
routes::{AdminError, AppError},
|
||||
startup::AppState,
|
||||
templates::MessageTemplate,
|
||||
templates::{EmailTemplate, MessageTemplate, StandaloneEmailTemplate},
|
||||
};
|
||||
use anyhow::Context;
|
||||
use askama::Template;
|
||||
@@ -27,8 +27,7 @@ pub struct BodyData {
|
||||
pub async fn insert_newsletter_issue(
|
||||
transaction: &mut Transaction<'static, Postgres>,
|
||||
title: &str,
|
||||
text_content: &str,
|
||||
html_content: &str,
|
||||
email_template: &dyn EmailTemplate,
|
||||
) -> Result<Uuid, sqlx::Error> {
|
||||
let newsletter_issue_id = Uuid::new_v4();
|
||||
let query = sqlx::query!(
|
||||
@@ -40,8 +39,8 @@ pub async fn insert_newsletter_issue(
|
||||
"#,
|
||||
newsletter_issue_id,
|
||||
title,
|
||||
text_content,
|
||||
html_content
|
||||
email_template.text(),
|
||||
email_template.html(),
|
||||
);
|
||||
transaction.execute(query).await?;
|
||||
Ok(newsletter_issue_id)
|
||||
@@ -56,9 +55,10 @@ pub async fn enqueue_delivery_tasks(
|
||||
r#"
|
||||
INSERT INTO issue_delivery_queue (
|
||||
newsletter_issue_id,
|
||||
subscriber_email
|
||||
subscriber_email,
|
||||
unsubscribe_token
|
||||
)
|
||||
SELECT $1, email
|
||||
SELECT $1, email, unsubscribe_token
|
||||
FROM subscriptions
|
||||
WHERE status = 'confirmed'
|
||||
"#,
|
||||
@@ -71,7 +71,9 @@ pub async fn enqueue_delivery_tasks(
|
||||
#[tracing::instrument(name = "Publishing a newsletter", skip(connection_pool, form))]
|
||||
pub async fn publish_newsletter(
|
||||
State(AppState {
|
||||
connection_pool, ..
|
||||
connection_pool,
|
||||
base_url,
|
||||
..
|
||||
}): State<AppState>,
|
||||
Extension(AuthenticatedUser { user_id, .. }): Extension<AuthenticatedUser>,
|
||||
Form(form): Form<BodyData>,
|
||||
@@ -90,7 +92,13 @@ pub async fn publish_newsletter(
|
||||
}
|
||||
};
|
||||
|
||||
let issue_id = insert_newsletter_issue(&mut transaction, &form.title, &form.text, &form.html)
|
||||
let email_template = StandaloneEmailTemplate {
|
||||
base_url: &base_url,
|
||||
text_content: &form.text,
|
||||
html_content: &form.html,
|
||||
};
|
||||
|
||||
let issue_id = insert_newsletter_issue(&mut transaction, &form.title, &email_template)
|
||||
.await
|
||||
.context("Failed to store newsletter issue details.")?;
|
||||
|
||||
|
||||
@@ -119,7 +119,5 @@ pub async fn create_newsletter(
|
||||
post_id,
|
||||
post_excerpt: "",
|
||||
};
|
||||
let html_content = template.render().unwrap();
|
||||
let text_content = template.text_version();
|
||||
insert_newsletter_issue(transaction, post_title, &text_content, &html_content).await
|
||||
insert_newsletter_issue(transaction, post_title, &template).await
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use crate::{routes::AppError, startup::AppState, templates::UnsubscribeTemplate};
|
||||
use crate::{
|
||||
routes::AppError,
|
||||
startup::AppState,
|
||||
templates::{NotFoundTemplate, UnsubscribeTemplate},
|
||||
};
|
||||
use anyhow::Context;
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
@@ -29,7 +33,11 @@ pub async fn unsubscribe(
|
||||
.context("Could not update subscriptions table.")?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
Ok(StatusCode::NOT_FOUND.into_response())
|
||||
Ok((
|
||||
StatusCode::NOT_FOUND,
|
||||
Html(NotFoundTemplate.render().unwrap()),
|
||||
)
|
||||
.into_response())
|
||||
} else {
|
||||
Ok(Html(UnsubscribeTemplate.render().unwrap()).into_response())
|
||||
}
|
||||
|
||||
@@ -63,8 +63,25 @@ pub struct NewPostEmailTemplate<'a> {
|
||||
pub post_excerpt: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> NewPostEmailTemplate<'a> {
|
||||
pub fn text_version(&self) -> String {
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/email/standalone.html")]
|
||||
pub struct StandaloneEmailTemplate<'a> {
|
||||
pub base_url: &'a str,
|
||||
pub html_content: &'a str,
|
||||
pub text_content: &'a str,
|
||||
}
|
||||
|
||||
pub trait EmailTemplate: Sync {
|
||||
fn html(&self) -> String;
|
||||
fn text(&self) -> String;
|
||||
}
|
||||
|
||||
impl<'a> EmailTemplate for NewPostEmailTemplate<'a> {
|
||||
fn html(&self) -> String {
|
||||
self.render().unwrap()
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
format!(
|
||||
r#"New post available!
|
||||
|
||||
@@ -86,10 +103,31 @@ Alphonse
|
||||
|
||||
zero2prod - Building better backends with Rust
|
||||
Visit the blog: {}
|
||||
Unsubscribe: {}/unsubscribe
|
||||
Unsubscribe: {}/unsubscribe?token=UNSUBSCRIBE_TOKEN
|
||||
|
||||
You're receiving this because you subscribed to the zero2prod newsletter."#,
|
||||
self.post_title, self.base_url, self.post_id, self.base_url, self.base_url,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> EmailTemplate for StandaloneEmailTemplate<'a> {
|
||||
fn html(&self) -> String {
|
||||
self.render().unwrap()
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
format!(
|
||||
r#"{}
|
||||
|
||||
---
|
||||
|
||||
zero2prod - Building better backends with Rust
|
||||
Visit the blog: {}
|
||||
Unsubscribe: {}/unsubscribe?token=UNSUBSCRIBE_TOKEN
|
||||
|
||||
You're receiving this because you subscribed to the zero2prod newsletter."#,
|
||||
self.text_content, self.base_url, self.base_url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user