透過C#發送MAIL,並且將發送的MAIL備份在指定的Folder底下
//寄出去的MAIL備份在C槽底下
string MailPath = "C:" + Path.DirectorySeparatorChar.ToString() + "DemoSendMail" + Path.DirectorySeparatorChar.ToString() + DateTime.Now.ToString("yyyyMMdd") + Path.DirectorySeparatorChar.ToString();
if (!Directory.Exists(MailPath))
{
Directory.CreateDirectory(MailPath);
}
//發送MAIL的時候寫一筆Log檔
string LogFile = MailPath + Path.DirectorySeparatorChar.ToString() + DateTime.Now.ToString("yyyyMMdd") + ".txt";
StreamWriter sw = new StreamWriter(LogFile, true);
try
{
MailMessage msg = new MailMessage();
msg.To.Add("");//收件者的EMail,多個收件者用逗號隔開
msg.From = new MailAddress("寄件者的MAIL", "寄件者名稱", System.Text.Encoding.UTF8);
msg.Subject = "Demo Send Mail" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
msg.IsBodyHtml = false;
msg.BodyEncoding = Encoding.UTF8;
msg.Body = "Demo Send Mail Content";
String SMTP = "smtp.gmail.com"; // 測試的時候用Gmail測試
int Port = 587; //25 or 587
String UserName = "寄件者帳號"; //
String PassWord = "寄件者密碼"; //
//建立 SmtpClient 物件 並設定 Gmail的smtp主機及Port
SmtpClient MySmtp = new SmtpClient(SMTP, Port);
//設定你的帳號密碼
MySmtp.Credentials = new System.Net.NetworkCredential(UserName, PassWord);
//Gmial 的 smtp 使用 SSL
MySmtp.EnableSsl = true;
//發送Email
MySmtp.Send(msg);
//oStemp (mail)放在本機;
SmtpClient oStemp = new SmtpClient(SMTP);
oStemp.UseDefaultCredentials = false;
//電子郵件會複製到 System.Net.Mail.SmtpClient.PickupDirectoryLocation 屬性所指定的目錄中,
oStemp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
//設定要備份的Folder路徑
oStemp.PickupDirectoryLocation = MailPath;
oStemp.Send(msg);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
sw.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + " Error:" + ex.Message);
}