using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Mail; using System.Net; using System.Net.Security; using System.IO; using System.Net.Mime; namespace SmtpTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { //定義一個mail對象 MailMessage mailmessage = new MailMessage(““, ““, “this is a test”, “yes!test!”); //from email,to email,主題,郵件內容 mailmessage.Priority = MailPriority.Normal; //郵件優先順序 SmtpClient smtpClient = new SmtpClient(“smtp.163.com”, 25); //smtp地址以及連接埠號碼 smtpClient.Credentials = new NetworkCredential(“ttlsa.com”, “xxxxxx”);//smtp使用者名稱密碼 smtpClient.EnableSsl = true; //啟用ssl //添加附件 Attachment attachment =null; if(listBox1.Items.Count>0) { for (int i = 0; i < listBox1.Items.Count; i++) { string pathFileName = listBox1.Items[i].ToString(); string extName = Path.GetExtension(pathFileName).ToLower(); //擷取副檔名 if(extName==”.rar”||extName==”.zip”) //.rar和.zip的檔案屬於壓縮檔類型 { attachment = new Attachment(pathFileName,MediaTypeNames.Application.Zip); }else { attachment = new Attachment(pathFileName,MediaTypeNames.Application.Octet); } //設定附件的MIME資訊 ContentDisposition cd = attachment.ContentDisposition; cd.CreationDate = File.GetCreationTime(pathFileName);//設定附件的建立時間 cd.ModificationDate = File.GetLastWriteTime(pathFileName);//設定附件的修改時間 cd.ReadDate = File.GetLastAccessTime(pathFileName);//設定附件的訪問時間 mailmessage.Attachments.Add(attachment);//將附件添加到mailmessage對象 } } smtpClient.Send(mailmessage); MessageBox.Show(“發送成功”); } catch (SmtpException se) { MessageBox.Show(se.StatusCode.ToString()); } } //添加附件,把檔案添加到listbox中 private void button2_Click(object sender, EventArgs e) { OpenFileDialog opd = new OpenFileDialog();//定義一個選擇檔案的對話方塊 opd.Multiselect = true;//允許選擇多個檔案 opd.CheckFileExists = true;//檢查檔案是否存在 opd.ValidateNames = true;//檢查檔案名稱的可用性 opd.ShowDialog();//開啟對話方塊 if(opd.FileNames.Length>0)//將選擇的檔案路徑寫入listbox中 { listBox1.Items.AddRange(opd.FileNames); } } } } |