如何用C#實(shí)現(xiàn)發(fā)送郵件?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
站在用戶的角度思考問(wèn)題,與客戶深入溝通,找到澠池網(wǎng)站設(shè)計(jì)與澠池網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:做網(wǎng)站、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、域名申請(qǐng)、網(wǎng)頁(yè)空間、企業(yè)郵箱。業(yè)務(wù)覆蓋澠池地區(qū)。#region 發(fā)送郵件部分 private static String fromMail = "1111@126.com"; ///郵箱名稱 private static String mailPwd = "111111"; ///密碼 private static string toMail = "2222@163.com"; ///郵箱服務(wù)器 private static string fileStr;//當(dāng)前圖片路徑,在添加附件時(shí)用 ////// 發(fā)送郵件 /// /// 附件地址,以~分 /// 是否發(fā)送截屏 ///public static string SendMail(string fileUrl, string screen) { MailAddress from = new MailAddress(fromMail); MailAddress to = new MailAddress(toMail); MailMessage message = new MailMessage(from, to); message.Subject = "M郵件 " +11111;//主題 message.SubjectEncoding = System.Text.Encoding.UTF8; Attachment attachFile = new Attachment(fileStr); if (screen == "True") message.Attachments.Add(attachFile); string[] files = fileUrl.Split('~'); for (int i = 0; i < files.Length; i++) { if (File.Exists(files[i])) { Attachment attachFile1 = new Attachment(fileUrl); message.Attachments.Add(attachFile1); } } try { SmtpClient client = new SmtpClient("smtp." + from.Host); SendMail(client, from, mailPwd, to, message); return "發(fā)送郵件成功!包含附件:" + fileUrl + " 含截圖?" + screen + " " + DateTime.Now.ToString(); } catch (SmtpException ex) { //如果錯(cuò)誤原因是沒(méi)有找到服務(wù)器,則嘗試不加smtp.前綴的服務(wù)器 if (ex.StatusCode == SmtpStatusCode.GeneralFailure) { try { //有些郵件服務(wù)器不加smtp.前綴 SmtpClient client = new SmtpClient(from.Host); SendMail(client, from, mailPwd, to, message); return "發(fā)送郵件成功!包含附件:" + fileUrl + " 含截圖?" + screen + " " + DateTime.Now.ToString(); } catch (SmtpException err) { return "發(fā)送郵件失敗!" + err.Message + " " + DateTime.Now.ToString(); } } else { return "發(fā)送郵件失??!" + ex.Message + " " + DateTime.Now.ToString(); } } } //根據(jù)指定的參數(shù)發(fā)送郵件 private static void SendMail(SmtpClient client, MailAddress from, string password, MailAddress to, MailMessage message) { //不使用默認(rèn)憑證,注意此句必須放在client.Credentials的上面 client.UseDefaultCredentials = false; //指定用戶名、密碼 client.Credentials = new NetworkCredential(from.Address, password); //郵件通過(guò)網(wǎng)絡(luò)發(fā)送到服務(wù)器 client.DeliveryMethod = SmtpDeliveryMethod.Network; try { client.Send(message); } catch { throw; } finally { //及時(shí)釋放占用的資源 message.Dispose(); } } #endregion
關(guān)于如何用C#實(shí)現(xiàn)發(fā)送郵件問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。