剛好需要在不特定機器上測試透過SMTP送信,想在不安裝任何開發工具的前題下跑一小段.NET程式測試SmtpClient,我立即想到Mini C# Lab

下面是使用Mini C# Lab測試SmtpClient的簡短程式,mail.To.Add加入收信者Email,mail.From為寄信者Email,設定mail.IsBodyHtml = true,mail.Body就可指定含HTML標籤的內容,mail.Subject中加入寄送時間以便區別,另外還用mail.Attachments.Add()加測附件功能。new SmtpClient("...")裡的參數請改成SMTP主機的IP,這樣子該測的應該都測到了,Check it out!yrh

using System;
using System.Net.Mail;
 
public class CSharpLab
{
    public static void Test()
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("jeffrey@mail.com");
        mail.From = new MailAddress("jeffrey@mail.com");
        mail.Subject = String.Format("Test @ {0:yyyy-MM-dd HH:mm:ss.fff}", 
            DateTime.Now);
        mail.Body = "<html><body><span style='color:red'>Test</span></body></html>";
        mail.IsBodyHtml = true;
        mail.Attachments.Add(new Attachment("b:\\test.txt"));
        SmtpClient smtp = new SmtpClient("192.168.1.25");
        smtp.Send(mail);
        Console.WriteLine("\nSent!");
    }
}

Comments

# by 路人喵

如果遇到smtp寄送mail需要驗證帳號密碼呢?

# by Jeffrey

to 路人喵, 可以參考這篇文章: http://demo.tc/Post/104

Post a comment