LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

使用C#和.Net通过SMTP发送邮件详解

admin
2017年11月8日 0:0 本文热度 7004

    到目前为止,发电子邮件已经不是什么新闻了,.Net中包含邮件客户端并不足为奇。一个老的编程事实任然有效:所有程序将扩大到包括最终发送(接收)的电子邮件。因此,如何增加电子邮件到您的程序?此帖探讨我们如何能够使用System.Mail.SmtpClient发送格式化电子邮件。有许多可供选择的选项,我们将探讨其中的大多数。

   十五年以后事情变得相当容易.发送电子邮件最直接的就是调用一些基本的库函数和.Net的一些固定的实现。

快速发送电子邮件
如果您迫不及待的话,可以使用下面带有4字符串参数的
构造函数创建一个简单的邮件。
// public client.Send(string from,string to,string subject,string body)
using System.Net.Mail;
SmtpClient client = new SmtpClient();
client.Send("
martijn@seamana.cn","test@seamana.cn","Testing!","If this break again,.. I won''t know what to do");
在上面的例子中的电子邮件使用系统的NET框架默认设置为发现的发送的。如果你对什么自己系统作为默认的SMTP服务器感到好奇,您可以查询SmtpClient.Host
Console.WriteLine("Default SMTP Server: {0}",client.Host);
请注意,有可能.NET libraries是无法制订SMTP主机,当您尝试发送电子邮件会失败并出现System.InvalidOperationException ( SMTP主机未指定)的异常。

发送一封合适的邮件
一个基本的电子邮箱是一个发件人,一个或多个收件人的邮件正文和一个或多个附件组成的。当然,电子邮件可能是一种过时的俄罗斯字体的编码
MailAddress toUser = new MailAddress("
martijn@seamana.cn");
MailAddress toUser2 = new MailAddress("
martijn@seamana.cn","Martijn Dijksterhuis");
MailAddress toUser3 = new MailAddress("
martijn@seamana.cn","Martijn Dijksterhuis", System.Text.Encoding.UTF8);
名字中不包括任何特殊的字符,所以指定默认的UTF - 8编码。
 
发送一封只有单一的发送和接收者的电子邮件
如果您的电子邮件只包含一个单一的发送者和一个接收者,MailMessage ( MailAddress From, MailAddress To)构造函数提供了所有您所需要的。它创建一个新的电子邮件的结构,分配发送者和接收者的构造方法。
MailAddress toUser = new MailAddress("
myfriend@yahoo.com");
MailAddress fromUser = new MailAddress("
aishijie36@hotmail.com");
MailMessage msg  = new MailMessage(fromUser,toUser);
 
增加更多相同的电子邮件的接收者
一个单一的收件人可能是不够的。不要担心,您可以添加许多人到你的电子邮件,只要你想。
msg.To.Add( new MailAddress("
second_to@seamana.cn") );
msg.CC.Add( new MailAddress("
first_cc@seamana.cn") );
 msg.CC.Add( new MailAddress("
second_cc@seamana.cn") );
msg.Bcc.Add( new MailAddress("
first_bcc@seamana.cn") );
 
设置电子邮件主题和内容
设置电子邮件的主题,并不难,只需通过Msg.Subject设置它 。如果你可以使用如Unicode的其他方式编码。
msg.Subject = "我的心太乱"
msg.SubjectEncoding = Encoding.GetEncoding("big5");
 
以非常类似的方式来设置邮件正文
msg.Body = "Dear Customer, " + Environment.NewLine + Environment.NewLine;
msg.Body += "Because of repeated violations of our terms and conditions we had no choice but to";
msg.Body += "terminate your account with us." + Environment.NewLine + Environment.NewLine;
msg.Body += "The Management";
msg.BodyEncoding = System.Text.Encoding.UTF8;
 
添加附件到电子邮件
电子邮件可以拥有一个以上的附件,每个附件的继承于System.Net.Mail.Attachment类。您可以通过调用" Attachments.Add ( ) "把它们添加到附件容器。
using System.Net.Mime;
Attachment firstAttachment = new Attachment("document.doc",MediaTypeNames.Application.Octet);
MailMessage msg  = new MailMessage(fromUser,toUser);
msg.Attachments.Add(firstAttachement);
 
第一个参数传递给构造函数是包含附件的路径。如果没有完整的路径,给出了当前的工作目录。该文件类型的在System.Net.Mime中定义 -可用选项有:
MediaTypeNamesApplicationOctet
  PDF
  RTF
  Soap
  Zip
 ImageGif
  JPEG
  Tiff
 TextHTML
  Plain
  RichText
  XML

如果该类型的文件未指定使用MediaTypesNames.Application.Octet ,怎显示"数据没有解释。 " 
 
添加自定义电子邮件标题到您的电子邮箱
Msg.Header属性允许查询和添加.NET框架所设定的电子邮件标题。全新的电子邮件将只包含一个标题: "Mine: 1.0 " 。
MailMessage Msg = new MailMessage(new  MailAddress("
martijn@seamana.cn"),newMailAddress("martijn@seamana.cn"));
 
// Add a custom header to the e-mail
Msg.Headers.Add("X-Header","2.0");
 
// Display all the message headers.
string[] Keys = Msg.Headers.AllKeys;
foreach (string s in Keys) 
Console.WriteLine("{0}: {1}", s,Msg.Headers[s]);
 
用SmtpClient发送电子邮件
  通过the SmtpClient class发送电子邮件的艰巨工作实际只需要下面两行代码:
SmtpClient client = new SmtpClient();
client.Send(Msg);
 
SmtpFailedRecipientsException: The message could not be delivered to one or more of the recipients in To, CC, or Bcc.
SmtpException : Connection failed, authentication failed or a time-out
ArgumentNullException / ArgumentOutOfRangeException / InvalidOperationException : Something wrong with the input fields of the e-mail
 
如果您没有指定任何参数,SmtpClient默认构造函数将查找使用.NET环境。
SMTP服务器
您可以通过第二构造方法指定一个特定的服务器和可选端口
SmtpClient client = new SmtpClient("mail.dijksterhuis.org",3000); 
 
上述SmtpClient.Send是阻塞调用-当电子邮件传送时您的应用程序应停止。当然也有一个

异步调用: SmtpClient.SendAsync 
使用SmtpClient.SendAsync是多做一点工作。如何做到这一点请看以下示例:
using System;

using System.Net.Mail;

using System.Threading;

using System.ComponentModel;

namespace SnmpMailer

  

  class MainClass   

        

   static Semaphore mailSendSemaphore;        

   private static void MailSendCallback(object sender, AsyncCompletedEventArgs arg)  

             

      // Get our unique token for this asynchronous operation.           

     String token = (string) arg.UserState;            

      // Did the user abort the sent ?           

     if (arg.Cancelled)               

        Console.WriteLine("[{0}] Send canceled.", token);         

      // Did an error occur during the send?           

     if (arg.Error != null)                

        Console.WriteLine("[{0}] {1}", token, arg.Error.ToString());              

      else               

        Console.WriteLine("Message sent succesfully!");            

      // Release the main thread           

      mailSendSemaphore.Release();       

            

 

  public static void Main(string[] args)       

            

   mailSendSemaphore = new Semaphore(0,1);   

   // Create the mail message with to & from   

    MailMessage Msg = new MailMessage(new MailAddress("noreply@dijksterhuis.org"), 

                    new MailAddress("martijn@dijksterhuis.org"));            

    Msg.Body = "Dear Customer, " + Environment.NewLine + Environment.NewLine;   

    Msg.Body += "Because of repeated violations of our terms and conditions we had

                no choice  but to";           

    Msg.Body += "terminate your account with us." + Environment.NewLine   

               Environment.NewLine;   

    Msg.Body += "The Management";           

    Msg.BodyEncoding = System.Text.Encoding.UTF8;   

    // Set the subject           

    Msg.Subject = "Termination of service notice"; 

    // Add our own header           

    Msg.Headers.Add("X-Deliverator","Terminator");    

    // Deliver the message in an asynchronous fashion           

    SmtpClient Deliverator = new SmtpClient("mymailserver.com");   

    // Print the default client           

    Console.WriteLine("Default SMTP Server: {0}",Deliverator.Host);  

    // Specify the call back function           

    Deliverator.SendCompleted += new SendCompletedEventHandle(MailSendCallback); 

    // For an asyncronous call we can pass a token to help us determine

    //  the message being send  

    Deliverator.SendAsync(Msg,"Msg ID 1212");   

    // Because we have little else to do, we set a semaphore and wait               

    mailSendSemaphore.WaitOne();            

    Console.WriteLine("Mail delivery finished");       

      

  }

}


该文章在 2017/11/8 0:00:48 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved