You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kentico自定义宏字段获取当前邮件收件人信息的方法问询

Kentico自定义宏字段获取当前邮件收件人

我尝试在自定义宏字段中获取当前邮件收件人数据,现有代码如下:

using CMS;
using CMS.DataEngine;
using CMS.MacroEngine;
using CMS.Membership;
//using CMSApp.CustomMethods;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

// Registers the custom module into the system
[assembly: RegisterExtension(typeof(EmailContactMacroFields), typeof(CustomContact))]

public class EmailContactMacroFields : MacroFieldContainer
{
    protected override void RegisterFields()
    {
        base.RegisterFields();

        // Defines a custom macro field in the container
        RegisterField(new MacroField("TestField", () => UserInfo.Provider.Get("administrator")));
        
    }
}

目前代码中使用UserInfo.Provider.Get("administrator")指定固定用户,我想替换为获取当前收件人,类似ContactProvider.CurrentRecipient的方式。我们希望在邮件模板中使用该自定义宏,是否可行?我知道可通过传递邮箱参数的自定义宏方法实现,但该方法无法在宏树视图中显示,因此必须使用宏字段。


解决方案

完全可行,只需修改宏字段的取值逻辑,从当前宏上下文(邮件模板执行环境)中获取收件人对象即可。以下是修改后的代码:

using CMS;
using CMS.DataEngine;
using CMS.MacroEngine;
using CMS.ContactManagement; // 添加ContactInfo所需的命名空间
using System;

// 注册自定义扩展到系统
[assembly: RegisterExtension(typeof(EmailContactMacroFields), typeof(CustomContact))]

public class EmailContactMacroFields : MacroFieldContainer
{
    protected override void RegisterFields()
    {
        base.RegisterFields();

        // 注册获取当前邮件收件人的宏字段
        RegisterField(new MacroField("CurrentRecipient", () => 
        {
            // 从宏上下文获取当前邮件收件人对象
            var recipient = MacroContext.Current.GetValue("Recipient") as ContactInfo;
            // 若未获取到则返回空的ContactInfo对象,避免空引用
            return recipient ?? ContactInfo.Provider.GetEmpty();
        }));
    }
}

// 自定义容器类,用于承载宏字段
public class CustomContact : MacroContainer { }

关键说明:

  • 宏上下文获取收件人:邮件模板执行时,Kentico会自动将当前收件人(ContactInfo对象)注入到MacroContext.Current的参数集合中,通过GetValue("Recipient")即可直接获取。
  • 宏树视图可见性:通过MacroFieldContainer注册的字段会自动出现在宏树视图中,你可以在邮件模板编辑器的宏选择面板里找到CurrentRecipient字段,展开后直接使用其属性(如FullName、Email、CompanyName等)。
  • 空值处理:添加空值判断,避免因上下文未注入收件人导致的空引用异常,确保代码健壮性。

内容的提问来源于stack exchange,提问作者chamara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:15:09