允许用户在Rails中为ActionMailer创建自定义电子邮件模板 [英] Allow user to create custom email template for ActionMailer in Rails

查看:79
本文介绍了允许用户在Rails中为ActionMailer创建自定义电子邮件模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许Rails应用程序的用户通过表单创建自己的电子邮件模板,并将其用作网站标准电子邮件模板表单,该表单将发送邮件,但我找不到任何教程,它也需要包含几个动态变量。

I want to allow the user of rails app to create their own email template via a form and use that as the sites standard email template form which mail will be sent but I can't find any tutorials, it also needs to contain a couple of dynamic variables.

是否有定义的方法来做到这一点?

Is there a defined way of doing this?

(因此用户会以引用变量
的形式输入电子邮件文本,该变量将在发送前进行评估)

( so the user would enter the email text in a form referencing variables that would be evaluated before being sent )

推荐答案

有很多方法您可以实现。这是一种方法。

There are many ways you can achieve it. Here is one way.

首先,您需要将用户生成的电子邮件模板存储在数据库中。

First of all, you need to store user-generated email templates in a database.

CustomEmailTemplate.create(user_id: params[:user_id], template_body: params[:template_body])

当需要发送模板电子邮件时,您将执行以下操作:

When it's time to send an email for the template, you would do something like:

custom_values = { name: "Whatever", value: "nice" }
template = CustomEmailTemplate.find(template_id)
CustomerEmailer.send_email(template, custom_values).deliver

要使其真正发挥作用,您需要在邮件程序中执行以下操作:

To make it really work, you need to do something like this in the mailer:

def send_email(template, custom_values)
    @template = template
    @custom_values = custom_values
    mail subject: "Your subject goes here.."
end

在send_email中.html.erb,请执行以下操作:

In the send_email.html.erb, do something like this:

<%= @template.template_text.gsub(/@@name@@/, @custom_values[:name]).gsub(/@@value@@/, @custom_values[:value]) %>

您会看到模板包含 @@ name @@和 @@ value @@ 。这些是您可以用自定义值替换的标记。

You see that the template contains "@@name@@" and "@@value@@". Those are the markers for you to be able to replace with custom values.

当然,您可以重构此代码以将替换逻辑放入模型中,等等。使其成为干净的代码。

Of course, you can refactor this code to put the substitution logic in the model, etc, to make it "clean code".

我希望这会有所帮助。

这篇关于允许用户在Rails中为ActionMailer创建自定义电子邮件模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆