发送带有图像的html电子邮件时使用Url.Content()

时间:2012-05-24 15:35:37

标签: asp.net html email image

我需要我的应用程序向用户发送确认电子邮件。我使用以下方法将视图呈现为字符串:

    public string RenderViewToString<T>(string viewPath, T model)
    {
        using (var writer = new StringWriter())
        {
            var view = new WebFormView(viewPath);
            var vdd = new ViewDataDictionary<T>(model);
            var viewCxt = new ViewContext(ControllerContext, view, vdd, new TempDataDictionary(), writer);
            viewCxt.View.Render(viewCxt, writer);
            return writer.ToString();
        }
    }

我从here得到的。它工作得很好,但我的图像没有被包括在内。我正在使用:

<img src="<%:Url.Content("~/Resource/confirmation-email/imageName.png") %>"

给了我

http://resource/confirmation-email/imageName.png

在网站上查看网页时,此功能正常,但图片链接无法在电子邮件中使用。

我需要它来给我:

http://domain.com/application/resource/confirmation-email/imageName.png

我也尝试过使用:

VirtualPathUtility.ToAbsolute()

2 个答案:

答案 0 :(得分:1)

这是我最近在网站上使用的内容:

public static string ResolveServerUrl(string serverUrl, bool forceHttps = false, bool getVirtualPath = true)
{
    if (getVirtualPath)
    serverUrl = VirtualPathUtility.ToAbsolute(serverUrl);

    if (serverUrl.IndexOf("://") > -1)
    return serverUrl;

    string newUrl = serverUrl;
    Uri originalUri = System.Web.HttpContext.Current.Request.Url;
    newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl;
    return newUrl;
}

然后我可以通过执行Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png");来使用它来生成绝对网址(假设您将静态函数包装在名为Core的类中)

HTH

答案 1 :(得分:0)

没有办法做到这一点。您可以添加以下扩展方法。

using System.Web.Mvc;

public static class UrlHelperExtensions
{
    public static string ToAbsoluteUrl(this UrlHelper helper, string relativeUrl) {
        if (Request.IsSecureConnection)
            return string.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
        else
            return string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
    }
}

然后你可以这样打电话

<img src="<%:Url.ToAbsoluteUrl("~/Resource/confirmation-email/imageName.png") %>" ...
相关问题