Skip to content

Commit 7e7949f

Browse files
yoyo930021claude
andcommitted
fix: preserve img style attribute through HTML sanitization
ammonia strips style attributes by default; explicitly allow style on <img> so that email layout styles (max-width:100%;height:auto;display:block) added by style_images_for_email survive sanitize_html. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 0e01608 commit 7e7949f

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/newsletter.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,13 @@ fn style_images_for_email(html: &str) -> String {
4141

4242
/// Sanitize HTML for public web display: strip `<script>`, event handlers,
4343
/// and other dangerous elements while preserving formatting tags.
44+
/// The `style` attribute on `<img>` is explicitly allowed so that
45+
/// email-client layout styles (max-width, height:auto, display:block) survive.
4446
pub fn sanitize_html(html: &str) -> String {
45-
ammonia::clean(html)
47+
ammonia::Builder::default()
48+
.add_tag_attributes("img", &["style"])
49+
.clean(html)
50+
.to_string()
4651
}
4752

4853
/// Replace `%recipient_name%` placeholder with the subscriber's name.
@@ -607,6 +612,13 @@ mod tests {
607612
assert!(result.contains("https://coscup.org"));
608613
}
609614

615+
#[test]
616+
fn test_sanitize_html_preserves_img_style() {
617+
let html = r#"<img src="https://example.com/img.png" style="max-width:100%;height:auto;display:block;">"#;
618+
let result = sanitize_html(html);
619+
assert!(result.contains(r#"style="max-width:100%;height:auto;display:block;""#));
620+
}
621+
610622
#[test]
611623
fn test_sanitize_html_preserves_formatting() {
612624
let html = r#"<h1>Title</h1><p><strong>Bold</strong> and <em>italic</em></p><ul><li>Item</li></ul>"#;

0 commit comments

Comments
 (0)