C# 發送郵件

來源:互聯網
上載者:User

MailAddress from = new MailAddress("gaosheng@hotmail.com", "高升"); //郵件的寄件者

MailMessage mail = new MailMessage();

//設定郵件的標題
mail.Subject = txtSubject.Text;

//設定郵件的寄件者
//Pass:如果不想顯示自己的郵箱地址,這裡可以填符合mail格式的任意名稱,真正發mail的使用者不在這裡設定,這個僅僅只做顯示用
mail.From = from;

//設定郵件的收件者
string address = "";
string displayName = "";
/**//*  這裡這樣寫是因為可能發給多個連絡人,每個地址用 ; 號隔開
  一般從地址簿中直接選擇連絡人的時候格式都會是 :使用者名稱1 < mail1 >; 使用者名稱2 < mail 2>;
  因此就有了下面一段邏輯不太好的代碼
  如果永遠都只需要發給一個收件者那麼就簡單了 mail.To.Add("收件者mail");
*/
string[] mailNames = (txtMailTo.Text + ";").Split(';');
foreach (string name in mailNames)
...{
    if (name != string.Empty)
    ...{
        if (name.IndexOf('<') > 0)
        ...{
            displayName = name.Substring(0, name.IndexOf('<'));
            address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
        }
        else
        ...{
            displayName = string.Empty;
            address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
        }
        mail.To.Add(new MailAddress(address, displayName));
    }
}

//設定郵件的抄送收件者
//這個就簡單多了,如果不想快點下崗重要檔案還是CC一份給領導比較好
mail.CC.Add(new MailAddress("Manage@hotmail.com", "尊敬的領導");

//設定郵件的內容
mail.Body = txtBody.Text;
//設定郵件的格式
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
//設定郵件的發送層級
mail.Priority = MailPriority.Normal;

//設定郵件的附件,將在用戶端選擇的附件先上傳到伺服器儲存一個,然後加入到mail中
string fileName = txtUpFile.PostedFile.FileName.Trim();
fileName = "D:\UpFile\" + fileName.Substring(fileName.LastIndexOf("\") + 1);
txtUpFile.PostedFile.SaveAs(fileName); // 將檔案儲存至伺服器
mail.Attachments.Add(new Attachment(fileName));

mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;

SmtpClient client = new SmtpClient();
//設定用於 SMTP 事務的主機的名稱,填IP地址也可以了
client.Host = "smtp.hotmail.com";
//設定用於 SMTP 事務的連接埠,預設的是 25
//client.Port = 25;
client.UseDefaultCredentials = false;
//這裡才是真正的郵箱登陸名和密碼,比如我的郵箱地址是 hbgx@hotmail, 我的使用者名稱為 hbgx ,我的密碼是 xgbh
client.Credentials = new System.Net.NetworkCredential("hbgx", "xgbh");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//都定義完了,正式發送了,很是簡單吧!
client.Send(mail);

本文來自:http://blog.csdn.net/hb_gx/archive/2008/04/16/2298945.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.