【问题标题】:C# Windows Form App to Send html formatted emailC# Windows 窗体应用程序发送 html 格式的电子邮件
【发布时间】:2020-05-29 10:24:12
【问题描述】:

我已经搜索了好几天,试图弄清楚如何使用我的 C# Windows 窗体应用程序将 html 格式的电子邮件从用户输入的文本框发送到某些电子邮件地址。我只找到了如何使用 ASP.net 来做到这一点,但我没有使用 ASP.net。只需要将电子邮件格式化为 html,并将其中的一部分替换为应用程序中的其他信息。这是我发现应该可以工作的东西,但我猜它只适用于 ASP.net:

private string PopulateBody(string userName, string title, string url, string description)
{
    string body = string.Empty;
    using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplate.htm")))
    {
        body = reader.ReadToEnd();
    }
    body = body.Replace("{UserName}", userName);
    body = body.Replace("{Title}", title);
    body = body.Replace("{Url}", url);
    body = body.Replace("{Description}", description);
    return body;
}

StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplate.htm")) 部分表示“服务器”无法使用。 是否有其他方法可以读取 html 模板并替换其中的项目然后发送到电子邮件地址?任何帮助表示赞赏!

【问题讨论】:

  • 这段代码没有发送电子邮件......它只是读取模板替换并返回 html 作为字符串......你是否尝试过一些明显的东西,比如用 @"O:\real\full\path\to\the\template.htm" 替换 Server.MapPath("~/EmailTemplate.htm")
  • 谢谢!

标签: c# winforms email smtp streamreader


【解决方案1】:

您需要获取可执行应用程序的本地路径,该应用程序可能不在 ASP.NET 服务器上下文中运行(因此您不能使用Server.MapPath())。您正在寻找的是这样的:

using (StreamReader reader = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate.htm")))

这应该尝试使用一个名为“EmailTemplate.htm”的文件打开一个流,该文件相对于可执行文件的位置(在同一文件夹中的旁边)。

查看这个 SO 问题以获取有关获取可执行文件夹路径的更多信息:Get current folder path

【讨论】:

    【解决方案2】:
    private string PopulateBody(string userName, string title, string url, string description)
    {
    string body = string.Empty;
    Assembly assembly = Assembly.GetExecutingAssembly();
    StreamReader reader =  new StreamReader(assembly.GetManifestResourceStream("YourProjectName.YourHTMLPageName.html"));
    
    body = reader.ReadToEnd();
    body = body.Replace("{UserName}", userName);
       body = body.Replace("{Title}", title);
       body = body.Replace("{Url}", url);
       body = body.Replace("{Description}", description);
    
    return body;
    }
    

    确保您已将 html 文件输入到您的项目中(复制,粘贴到您的项目文件夹中)从刷新图标刷新项目然后写入单击 html 文件,然后选择包含,然后选择属性,然后从构建操作组合框中选择来自它的嵌入式资源

    用于校准的img链接 ::: https://www.dropbox.com/s/ec2iy7qtv4kvc0n/stack.JPG?dl=0

    【讨论】:

    • 请添加此代码在做什么的描述。此外,编辑似乎处于活动状态,但此代码应使用栅栏并应格式化。
    猜你喜欢
    • 1970-01-01
    • 2013-03-10
    • 2014-01-14
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2014-06-22
    相关资源
    最近更新 更多