一些關於C#發送郵件的代碼


1.命名空間 using System.Net.Mail;

2.創建一個MailMessage類的對象

 

[csharp]  view plain copy
 
  1. MailMessage mail = new MailMessage(); 
[csharp]  view plain  copy
 
  1. MailMessage mail = new MailMessage();  

 

3.設置郵件的各種屬性

 

//設置郵件的標題             

mail.Subject = "測試郵件";             

//設置郵件的發件人            

mail.From = new MailAddress("leowangzi@163.com","Leo");           

//設置郵件的收件人             

mail.To.Add(new MailAddress("lichao.wang@amusegroup.com","Daniel"));        

//設置郵件的抄送人             

mail.CC.Add(new MailAddress("nick.yin@amusegroup.com","Nick"));       

//設置郵件的內容             

mail.Body = "就是測試用";         

[csharp]  view plain  copy
 
  1. mail.Body = "就是測試用";              
 

//設置郵件的格式    

[csharp]  view plain  copy
 
  1. //設置郵件的格式              
mail.BodyEncoding = System.Text.Encoding.UTF8;         
[csharp]  view plain  copy
 
  1. mail.BodyEncoding = System.Text.Encoding.UTF8;              
 
mail.IsBodyHtml =  true;        
[csharp]  view plain  copy
 
  1. mail.IsBodyHtml = true;              
 

////設置郵件的發送級別         

[csharp]  view plain  copy
 
  1. ////設置郵件的發送級別              
 mail.Priority = MailPriority.Normal;        
[csharp]  view plain  copy
 
  1. mail.Priority = MailPriority.Normal;             
 

mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;       

[csharp]  view plain  copy
 
  1. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;              
 

SmtpClient client = new SmtpClient();      

[csharp]  view plain  copy
 
  1. SmtpClient client = new SmtpClient();              
 

//設置用於 SMTP 事務的主機的名稱,填IP地址也可以了         

[csharp]  view plain  copy
 
  1. //設置用於 SMTP 事務的主機的名稱,填IP地址也可以了              
 

client.Host = "smtp.163.com";        

[csharp]  view plain  copy
 
  1. client.Host = "smtp.163.com";              
 

//設置用於 SMTP 事務的端口,默認的是 25         

[csharp]  view plain  copy
 
  1. //設置用於 SMTP 事務的端口,默認的是 25              
 

//client.Port = 25;     

[csharp]  view plain  copy
 
  1. //client.Port = 25;              
 

client.UseDefaultCredentials = false;        

[csharp]  view plain  copy
 
  1. client.UseDefaultCredentials = false;              
 

client.Credentials = new System.Net.NetworkCredential("leowangzi@163.com","*******");             

[csharp]  view plain  copy
 
  1. client.Credentials = new System.Net.NetworkCredential("leowangzi@163.com", "*******");              
 

client.DeliveryMethod = SmtpDeliveryMethod.Network;         

[csharp]  view plain  copy
 
  1. client.DeliveryMethod = SmtpDeliveryMethod.Network;              
 

//都定義完了,正式發送了!            client.Send(mail); 

[csharp]  view plain  copy
 
  1. //都定義完了,正式發送了!            client.Send(mail);  

 

 

4.當需要發送多人時

 

[csharp]  view plain copy print ?
 

string displayName = ""; 

[csharp]  view plain  copy
 
  1. string displayName = "";  
string[] mailNames = (txtMailTo.Text +";").Split(';'); 
[csharp]  view plain  copy
 
  1. string[] mailNames = (txtMailTo.Text + ";").Split(';');  
foreach (string namein mailNames) 
[csharp]  view plain  copy
 
  1. foreach (string name in mailNames)  
 {   
       if (name !=string.Empty)     
[csharp]  view plain  copy
 
  1. {    if (name != string.Empty)      
      {        
            mail.To.Add( new MailAddress(name , displayName));  
      } 
[csharp]  view plain  copy
 
  1. {         mail.To.Add(new MailAddress(name , displayName));   }  
 } 
[csharp]  view plain  copy
 
  1. }  

 

 

5.當需要發送附件時

 

//設置郵件的附件,將在客戶端選擇的附件先上傳到服務器保存一個,然后加入到mail中 
[csharp]  view plain  copy
 
  1. //設置郵件的附件,將在客戶端選擇的附件先上傳到服務器保存一個,然后加入到mail中  
 

string fileName = txtUpFile.PostedFile.FileName.Trim(); 

[csharp]  view plain  copy
 
  1. string fileName = txtUpFile.PostedFile.FileName.Trim();  
 

fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1); 

[csharp]  view plain  copy
 
  1. fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);  
 

txtUpFile.PostedFile.SaveAs(fileName);  

[csharp]  view plain  copy
 
  1. txtUpFile.PostedFile.SaveAs(fileName);   
 

// 將文件保存至服務器mail. 

[csharp]  view plain  copy
 
  1. // 將文件保存至服務器mail.  
 

Attachments.Add(new Attachment(fileName)); 

[csharp]  view plain  copy
 
  1. Attachments.Add(new Attachment(fileName));  

 

 

6.也可以這么發送附件

//Attachment 

            string strFilePath = @"C:\test.jpg"; 

            Attachment at = new Attachment(strFilePath); 

            at.Name = System.IO.Path.GetFileName(strFilePath); 

            at.NameEncoding = System.Text.Encoding.GetEncoding("gb2312"); 

            at.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; 

            at.ContentDisposition.Inline = true; 

            at.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline; 

            string cid = at.ContentId; 

            mail.Attachments.Add(at); 

[csharp]  view plain  copy
 
  1. //Attachment  
  2.             string strFilePath = @"C:\test.jpg";  
  3.             Attachment at = new Attachment(strFilePath);  
  4.             at.Name = System.IO.Path.GetFileName(strFilePath);  
  5.             at.NameEncoding = System.Text.Encoding.GetEncoding("gb2312");  
  6.             at.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;  
  7.             at.ContentDisposition.Inline = true;  
  8.             at.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline;  
  9.             string cid = at.ContentId;  
  10.             mail.Attachments.Add(at);  


7.另外的說明

 

●MailMessage類,用於構造電子郵件
●MailAttachment類,用於構造電子郵件附件
●SmtpMail類,用於發送電子郵件及其附件
1、MailMessage類構造電子郵件
此類主要有以下屬性和方法
★From     發件人的地址
★To       以分號分隔的收件人的地址列表
★Cc       以分號隔開的抄送的收件人的郵件地址列表
★Subject  電子郵件的主題
★Body     電子郵件的正文
★BodyFormat 電子郵件的正文內容類型,由MailFormat枚舉值指定,MailFormat.Text或MailFormat.Html
★Attachments 電子郵件附件集合
★Priority  電子郵件的優先級,由MailPriority枚舉值指定,可以是MailPriority.Low ,MailPriority.Normal或MailPriority.High三者之一
2、Attachment用來構造電子郵件附件.用此類構造了電子郵件附件然后添加到MailMessage對象的Attachments集合即可
3、使用SmtpMail類發送電子郵件,可以通過系統本身的SMTP郵件服務或者其它SMTP服務器來發送,發送電子郵件首先需要設置SmtpMail類的SmtpServer屬性,然后使用Send方法發送就可以了

 

8.關於HTML

 

  1. HTML格式郵件中,嵌入圖片資源
  2. 要求收到后,發送回執給你
  3. 如果郵件發送失敗, 發送錯誤通知郵件給你
  4. 支持 HTML/plain text 雙格式的郵件, 收件端可以自行切換
  5. 自定義郵件頭
  6. 異步發送, 支持取消發送
  7. 郵件回執, 支持 Lotus Notes 的 domino server
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Host = "smtp.163.com";
smtp.Credentials = new NetworkCredential("三角貓@163.com", "這是密碼");

MailMessage mm = new MailMessage();
mm.From = new MailAddress("三角貓@163.com", "三角貓", Encoding.GetEncoding(936));
mm.To.Add("三角貓@gmail.com");

mm.SubjectEncoding = Encoding.GetEncoding(936);
mm.Subject = "三角貓發的測試郵件,呵呵";

mm.BodyEncoding = Encoding.GetEncoding(936);

////普通文本郵件內容,如果對方的收件客戶端不支持HTML,這是必需的
string plainTextBody = "如果你郵件客戶端不支持HTML格式,或者你切換到“普通文本”視圖,將看到此內容";
mm.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainTextBody, null, "text/plain"));

////HTML格式郵件的內容
string htmlBodyContent = "如果你的看到<b>這個</b>, 說明你是在以 <span style=\"color:red\">HTML</span> 格式查看郵件<br><br>";
htmlBodyContent += "<a href=\"http://www.zu14.cn/\">真有意思網</a> <img src=\"cid:weblogo\">";   //注意此處嵌入的圖片資源
AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html");

////處理嵌入圖片
LinkedResource lrImage = new LinkedResource(@"d:\blogo.gif", "image/gif");
lrImage.ContentId = "weblogo"; //此處的ContentId 對應 htmlBodyContent 內容中的 cid:  ,如果設置不正確,請不會顯示圖片
htmlBody.LinkedResources.Add(lrImage);

mm.AlternateViews.Add(htmlBody);

////要求回執的標志
mm.Headers.Add("Disposition-Notification-To", "接收回執的郵箱@163.com");

////自定義郵件頭
mm.Headers.Add("X-Website", "http://www.zu14.cn/");

////針對 LOTUS DOMINO SERVER,插入回執頭
mm.Headers.Add("ReturnReceipt", "1");

mm.Priority = MailPriority.Normal; //優先級
mm.ReplyTo = new MailAddress("回復郵件的接收地址@yahoo.com.cn", "我自己", Encoding.GetEncoding(936));

////如果發送失敗,SMTP 服務器將發送 失敗郵件告訴我
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

////異步發送完成時的處理事件
smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);

////開始異步發送
smtp.SendAsync(mm, null);
void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("發送被取消");
            }
            else
            {
                if (e.Error == null)
                {
                    MessageBox.Show("發送成功");
                }
                else
                {
                    MessageBox.Show("發送失敗: " + e.Error.Message);
                }
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM