0

これまで、プログラムで電子メール通知を生成して送信したことはありません。私がする必要があるのは、このプログラムがファイルの移動に失敗した場合、または例外が発生して電子メールを生成し、(できれば) Log.txt ファイルを電子メールに添付して送信する場合です。このアプリはエンタープライズ スケジューラから実行され、ファイルとフォルダーを管理するために 1 時間に 1 回実行されます。

これが私が現在持っている機能コードです(メールの実装はまだありません)メールを送信したい場所にコメントしました

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;

namespace FileOrganizer
{
   class Program
   {
      //These are the folder to organize and delimeter that is in the filenames to split off a folder from
      static string folder = ConfigurationManager.AppSettings["folder"]; //"C:\Users\MyUserName\Desktop\Organize Me"
      static string delim = ConfigurationManager.AppSettings["delim"]; // delim = "__"

      //location for the log.txt file
      static string logPath = ConfigurationManager.AppSettings["logPath"]; //C:\Users\MyUserName\Desktop\Log.txt

      //contact list from the app.config
      static string emailTo = ConfigurationManager.AppSettings["notifyEmailAddress"]; //multiple email addresses delimited by a ; example = tom@domain.com;dick@differentDomain.com;harry@domain.com

      //for the log.txt reporting
      static int filesMoved = 0;
      static int filesNOTmoved = 0;
      static string fileNamesNOTmoved = "";
      static int foldersCreated = 0;
      static string message = "";
      static string stackTrace = "";
      //used for passing all the objects into the log method
      static object[] details = new object[6];

      static void Main(string[] args)
      {
         try
         { 
            using (StreamWriter w = File.AppendText(logPath))
            {
               int total = organizeFolder(delim, folder);
               details[0] = filesMoved;
               details[1] = filesNOTmoved;
               details[2] = fileNamesNOTmoved;
               details[3] = foldersCreated;
               details[4] = "No Errors Found";
               details[5] = "No Errors Found";
               Log(details, w);
               if (filesNOTmoved > Convert.ToInt32(filesNOTmoved))
               {
                  //generate email to notify of filesNames not moved (prefer to send Log.txt as attachment)
               }
            }
            using (StreamReader r = File.OpenText(logPath))
            {
               DumpLog(r);
            }
         }
         catch (Exception ex)
         {
            using (StreamWriter w = File.AppendText(logPath))
            {
               details[0] = filesMoved;
               details[1] = filesNOTmoved;
               details[2] = fileNamesNOTmoved;
               details[3] = foldersCreated;
               details[4] = ex.Message.ToString();
               details[5] = ex.StackTrace.ToString();
               Log(details, w);
            }
            //generate email to notify of Error and (prefer to send Log.txt as attachment)
            using (StreamReader r = File.OpenText(logPath))
            {
               DumpLog(r);
            }
         }   
      }   

      /*Takes a folder and organizes it into folder by naming folder whatever 
       * is in front of the delimeter Example -->(folderName__fileName.txt would be moved 
       * to a new or existing folder named folderName.  Final path for file would 
       * look like this folderName\folderName__fileName.txt)
       * 
       * It will not move file if it already exists in the new location, instead
       * it prompts user that they should rename file and run program again.*/
       static int organizeFolder(string delimeter, string rootPath)
       {
          //counter for total files in Folder
          int Count = 0;
          int totalMoved = 0;

          FileInfo[] fileNames;
          DirectoryInfo di = new DirectoryInfo(rootPath);

          //set all file names as a string from network directory into an array  
          fileNames = di.GetFiles("*.*");
          Count = fileNames.Length;

          //Count = 0;//just to test exception handling

          //if no files exist in network folder throw error message.
          if (Count == 0)
          {
             fileNamesNOTmoved = "No Files Were In Directory to Move."; 
          }
          else //files exist in network folder
          {
             int delimIndex = 0;
             string folderName;
             for (int i = 0; i < Count; i++)
             {
                if (fileNames[i].ToString().Contains(delimeter))
                {
                   delimIndex = fileNames[i].ToString().IndexOf(delimeter);
                   folderName = fileNames[i].ToString().Substring(0, delimIndex);
                   //if folder doesnt exist create it here.
                   folderCreation(rootPath, folderName);
                   if (!File.Exists(rootPath + @"\" + folderName + @"\" + fileNames[i].Name))
                   {
                      File.Move(rootPath + @"\" + fileNames[i].ToString(), rootPath + @"\" + folderName + @"\" + fileNames[i].Name);
                      filesMoved++;
                   }
                   else
                   {
                      if (fileNamesNOTmoved == "")
                         fileNamesNOTmoved += "| ";
                      fileNamesNOTmoved += fileNames[i].Name + " | ";
                      filesNOTmoved++;
                   }
                   totalMoved++;
                }
             }
          } 
          return totalMoved;
       }

       //if folder does not exist this method will create it
       private static void folderCreation(string strTempPath, string folderName)
       {
          strTempPath = strTempPath + @"\" + folderName;
          if (!Directory.Exists(strTempPath))
          {
             //Create \folderName
             Directory.CreateDirectory(strTempPath);
             foldersCreated++;
          }
       }

       //adds entries to the log.txt file
       public static void Log(object[] details, TextWriter w)
       {
          w.Write("\r\nLog Entry : ");
          w.WriteLine("{0} {1}", DateTime.Now.ToShortTimeString(), DateTime.Now.ToShortDateString());
          w.WriteLine("  :");
          w.WriteLine("  :{0}", "Files Moved = " + details[0].ToString());
          w.WriteLine("  :{0}", "Folders Created = " + details[3].ToString());
          w.WriteLine("  :{0}", "Files Not Moved = " + details[1].ToString());
          w.WriteLine("  :{0}", "Files Names Not Moved = {" + details[2].ToString() + "}");
          w.WriteLine("  :{0}", "Error Message = " + details[4].ToString());
          w.WriteLine("  :{0}", "Error Stack Trace = " + details[5].ToString());
          w.WriteLine("---------------------------------------------------------------------------------------");
       }

       public static void DumpLog(StreamReader r)
       {
          string line;
          while ((line = r.ReadLine()) != null)
          {
             Console.WriteLine(line);
          }
       }
    }
}   

基本的に、メールには次のように記載してください。

  1. 件名: データ管理エラー通知
  2. 本文: これは、ディレクトリ内のファイルをクリーンアップしようとしてエラーが発生したことを通知する自動生成メールです。詳細については、添付の Log.txt ファイルを参照してください。
  3. 添付ファイル: Log.txt
4

1 に答える 1

0

結局のところ、SMTP が最適でした。ローカル マシンの制限により、Dev、Qua、および Prd サーバーからしかアクセスできませんでした。これらの場所のいずれかから管理者としてテストされると、電子メールは完全に送信されます!!!

App.Config を使用してすべての To、From、SMTP ホスト情報を保持し、HTML を文字列オブジェクトとしてメソッドに渡します。これは、私が電子メールを送信するために使用したメソッドです。

    public static void sendMail(string msg)
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress(emailFrom);
        smtpClient.Host = smtpHost;
        message.From = fromAddress;
        message.Subject = "Test Email";
        message.IsBodyHtml = true;
        message.Body = msg;
        message.To.Add(emailTo);
        message.Priority = MailPriority.High;
        smtpClient.Send(message);
    }
于 2013-12-10T19:49:50.833 に答える