如何使用 C# 在控制台应用程序中格式化电子邮件通知的布局

How to format the layout of email notifications in Console Application using C#

首先,我查看了被认为相似但 none 解决了我当前问题的建议问题。

我编写了一个控制台应用程序,用于监控驻留在我们 DMZ 服务器中的多个应用程序(目前总共五个),并每天四次通知用户是否有任何或所有应用程序处于 UP 或 DOWN 状态。

目前,当您 运行 该应用程序时,它只需在电子邮件主题中指明应用程序是关闭还是启动即可运行。

以下是当前有效的电子邮件功能:

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Text;
using System.Configuration;

namespace showserverstatus
{
    class Program
    {
        static int Main(string[] args)
        {
           int result = 0;
            foreach (string site in args)
            {
                if (!ServerStatusBy(site))
                {
                    result++;
                }
            }

            return result;

        }

        static bool ServerStatusBy(string site)
        {
            Ping pingSender = new();
            PingReply reply = pingSender.Send(site, 10000);
            if (reply.Status != IPStatus.Success)
            {
                SendEmail($"{site} DOWN", $"Ping {site}");
                return false;
            }
            SendEmail($"{site} UP", $@"Ping {site}");

            return true;
        }
        public static void SendEmail(string subject, string body)
        {
            using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "myemail@gmail.com");
            mm.To.Add("myemail@gmail.com");
            mm.CC.Add("myother@att.net");
            mm.Subject = subject;
            mm.Body = body;
            mm.IsBodyHtml = false;

            SmtpClient smtp = new()
            {
                Host = ConfigurationManager.AppSettings["Host"],
                Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
                EnableSsl = true,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
            };

            Console.WriteLine("Sending email...");
            smtp.Send(mm);
            Console.WriteLine("Email sent.");
            System.Threading.Thread.Sleep(3000);
        }
    }
}

目前的挑战是如何格式化发送给我们高管的电子邮件的布局,以便电子邮件主题为: DMZ 服务器上的应用程序状态

邮件正文如下: 请在下面找到 DMZ 服务器的状态: 然后是应用程序列表,一行一个应用程序。

非常感谢任何帮助,

您需要存储 ping 结果并在所有站点都 ping 后发送一封电子邮件:

static void Main(string[] args) {
    var siteToStatus = new Dictionary<string, string>();
    foreach (var site in args) {
        var reply = new Ping().Send(site, 10000);
        siteToStatus[site] = (reply.Status == IPStatus.Success) ? "UP" : "DOWN";
    }
    var subject = "Status Of Applications on DMZ Server";
    var body = "Please find the status of the DMZ servers below:";
    foreach (var kvp in siteToStatus) {
        body += $"{Environment.NewLine}{kvp.Key}: {kvp.Value}"; // e.g. "google.com: UP"
    }
    SendEmail(subject, body);
}