如何使用MailKit發送電子郵件?

最近發現有一支程式就唯獨在某台電腦上該程式內的e-mail就發不出去了,所以重新檢視一下收發電子郵件的程式及說明,發現在微軟的smtpClient Class文件中提到 SmtpClient Class 因不支援一些新的協議(protocol),在某些平台上已過時,不推薦在其他平台上使用。並指明改用 MailKit [備註1]或其他 Liberary。但是,如果平台上包含有.NET Standard 2.0(或更高版本)、.NET Framework 4 到 .NET Framework 4.8、.NET Core 仍可使用。[備註3]

所以就試著使用MailKit來收發電子郵件而不使用smtpClient Class,如下:

1. 在 Microsoft Visual Studio上安裝 MailKit

2. 使用 MailKit 發送電子郵件--C#程式範例

3. 相關參考文件

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. 在 Microsoft Visual Studio上安裝 MaiKit

第一次使用MailKit前須先安裝此套件[備註5],安裝步驟如下:

1.1 工具 > NuGet 套件管理員(N) > 管理方案的NuGet套件(N)…

1.2 在[瀏覽]下方的格子輸入mailkit > 點選[MailKit…項下載] > 出現右側[專案]名稱及是否[已安裝]資訊 > 勾選[專案] > 點選[安裝]。

1.3 點選[確定]繼續進行安裝。

1.4 [已安裝]訊息變為版本編號,表示安裝完成。


2. 使用 MailKit 發送電子郵件--C#程式範例
internal static bool SendEmailByMailKit(
    string FromName,    string FromAddress,
    string ToName,      string ToAddress,
    string CcName,      string CcAddress,
    string BccName,     string BccAddress,
    string SubjectText, string BodyText,    string AttachedFile)
{
    bool success = false;
    var message = new MimeMessage();
    var bodybuilder = new BodyBuilder();    // Using BodyBuilder for email content            
    //
    try
    {
        message.From.Add(new MailboxAddress(FromName, FromAddress));
        message.To.Add(new MailboxAddress(ToName, ToAddress));
        if(!string.IsNullOrEmpty(CcAddress))
            message.Cc.Add(new MailboxAddress(CcName, CcAddress));
        if (!string.IsNullOrEmpty(BccAddress))
            message.Bcc.Add(new MailboxAddress(BccName, BccAddress));
        message.Subject = "[TEST]" + SubjectText;                

        bodybuilder.TextBody = "[This is a plain text]\n\n" + BodyText;
        //or
        //bodybuilder.HtmlBody = "<b>[This is a html text]</b>" +  BodyText;

        if (!string.IsNullOrEmpty(AttachedFile))
            bodybuilder.Attachments.Add(AttachedFile);
        
        message.Body = bodybuilder.ToMessageBody();

        if(!string.IsNullOrEmpty(FromAddress))
        {
            string[] subs = FromAddress.Split('@');
            string mailhost = subs[1];

            var client = new MailKit.Net.Smtp.SmtpClient();
            client.Connect(mailhost, 587, MailKit.Security.SecureSocketOptions.None);
            // or 
            //client.Connect(mailhost, 25, MailKit.Security.SecureSocketOptions.None);
            client.Send(message);
            client.Disconnect(true);
            success = true;
        }                
    }
    catch (Exception e)
    {
        string errormessage = e.ToString();
        success = false;
    }            
    return success;
}
Read More »

如何操作Windows的文字檔(使用C#來建立、讀取、刪除檔案...)?

  •  如何判斷資料夾是否存在 :

if (System.IO.Directory.Exists(mypath))
    return true;
  • 如何建立一個資料夾:

Directory.CreateDirectory(mypath);

  • 如何建立一個文字檔並寫入一串文字:

if (!File.Exists(myfile))
{
    StreamWriter sw = File.CreateText(myfile);    //建立一個文字檔
    sw.WriteLine("my message...");                //寫入一串文字                      
    sw.Close();
}

  • 如何寫入一串文字到既有的文字檔內:

if (!File.Exists(myfile))
{
    StreamWriter sw = new StreamWriter(myfile, true);    //已存在的文字檔
    sw.WriteLine("my message...");                       //寫入一串文字               
    sw.Close(); }

  • 如何搬移檔案(將檔案搬到另一個資料夾):

File.Move(mySourcePathFile, myTargetPathFile);

  • 如何刪除一個檔案:

File.Delete(myfile);  

  • 如何讀取某一資料夾下的所有檔案:

string[] myfiles = System.IO.Directory.GetFiles(mypath);
foreach (string myfile in myfiles)
    myfilename = Path.GetFileName(myfile);    //myfile contains path & file.

  • 如何讀取檔案的內容(一次讀一行):

foreach (string line in File.ReadLines(myfile))

    string[] substring = line.Split(' ');

  • 如何判斷檔案內容是否為空白?

if (new FileInfo(myfilen).Length == 0)      
  retur true;  

  • 如何合併檔案路徑(資料夾)和檔名 :

string mypath = "...";
string myfile = "...";
string mypathfile = Path.Combine(mypath, myfile);

參考網站 : 檔案系統和登錄-c # 程式設計指南 | Microsoft Docs https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/file-system/



Read More »
>