一些关于C#发送邮件的代码

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

2.创建一个MailMessage类的对象

 

[csharp] view plaincopy
 
  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 plaincopyprint?
 

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);
                }
            }
        }
posted @ 2017-05-17 23:40  jeremy1888  阅读(2293)  评论(0编辑  收藏  举报