Premailex 项目使用教程

Premailex 项目使用教程

premailexPreflight for your HTML emails - inline styling and plain text.项目地址:https://gitcode.com/gh_mirrors/pr/premailex

项目介绍

Premailex 是一个用于 HTML 邮件内联样式和纯文本转换的开源项目。它可以帮助开发者将 HTML 邮件中的 CSS 样式转换为内联样式,并生成相应的纯文本版本,以便在各种邮件客户端中更好地显示。Premailex 支持多种 HTML 解析器,如 Floki 和 Meeseeks,并且可以与常用的邮件库(如 Swoosh 和 Bamboo)集成。

项目快速启动

安装

首先,确保你已经安装了 Elixir 和 Mix。然后,在你的项目中添加 Premailex 依赖:

defp deps do
  [
    {:premailex, "~> 0.3.19"}
  ]
end

运行以下命令安装依赖:

mix deps.get

使用示例

以下是一个简单的使用示例,展示了如何将 HTML 字符串转换为内联样式和纯文本:

html = """
<html>
  <head>
    <style>
      p {
        color: blue;
      }
    </style>
  </head>
  <body>
    <p>Hello, World!</p>
  </body>
</html>
"""

# 转换为内联样式
inline_html = Premailex.to_inline_css(html)

# 转换为纯文本
text = Premailex.to_text(html)

IO.puts("Inline HTML: #{inline_html}")
IO.puts("Text: #{text}")

应用案例和最佳实践

与 Swoosh 集成

Swoosh 是一个流行的 Elixir 邮件库。以下是如何将 Premailex 与 Swoosh 集成的示例:

def welcome(user) do
  new()
  |> to([{user.name, user.email}])
  |> from({"Dr B Banner", "hulk.smash@example.com"})
  |> subject("Hello Avengers")
  |> render_body("welcome.html", %{username: user.name})
  |> premail()
end

defp premail(email) do
  html = Premailex.to_inline_css(email.html_body)
  text = Premailex.to_text(email.html_body)
  email
  |> html_body(html)
  |> text_body(text)
end

与 Bamboo 集成

Bamboo 是另一个常用的 Elixir 邮件库。以下是如何将 Premailex 与 Bamboo 集成的示例:

def welcome_email do
  new_email()
  |> subject("Email subject")
  |> to("test@example.com")
  |> from("test@example.com")
  |> put_text_layout(false)
  |> render("email.html")
  |> premail()
end

defp premail(email) do
  html = Premailex.to_inline_css(email.html_body)
  text = Premailex.to_text(email.html_body)
  email
  |> html_body(html)
  |> text_body(text)
end

典型生态项目

Floki

Floki 是一个用于解析和查询 HTML 的 Elixir 库,Premailex 默认使用 Floki 作为 HTML 解析器。

Meeseeks

Meeseeks 是另一个用于解析和查询 HTML 的 Elixir 库,Premailex 也支持使用 Meeseeks 作为 HTML 解析器。你可以通过以下配置切换到 Meeseeks:

config :premailex, html_parser: Premailex.HTMLParser.Meeseeks

Swoosh 和 Bamboo

Swoosh 和 Bamboo 是两个流行的 Elixir 邮件库,它们都可以与 Premailex 集成,以便在发送邮件时自动处理内联样式和纯文本转换。

通过这些集成,你可以确保你的 HTML 邮件在各种邮件客户端中都能正确显示,并提供良好的用户体验。

premailexPreflight for your HTML emails - inline styling and plain text.项目地址:https://gitcode.com/gh_mirrors/pr/premailex

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华建万

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值