在net2.0中,如何通过程序直接发送邮件,这是很多朋友都关注的问题,下面本人详细介绍该功能如何使用:
首先添加如下的引用:
using System.Net.Mail;
下面是发送邮件的代码:
MailAddress EmailFrom =new MailAddress("Emaster@126.com");
MailAddress EmailTo = new MailAddress("收件人地址");
MailMessage Email = new MailMessage(EmailFrom, EmailTo);
Email.Priority = MailPriority.High;
Email.Subject = "大众计算机学习网发送给您的邮件";
Email.Body = "邮件内容在附件里面,请自行打开!";
//添加抄送电子邮件
Email.CC.Add("这里就是你发送邮件的目标拉,填写抄送收件人的邮件地址");
string file = Server.MapPath("EmailAttachment\\") + "Data.rar";//附件路径
Attachment data = new Attachment(file,System.Net.Mime.MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
Email.Attachments.Add(data);
SmtpClient Client = new SmtpClient("smtp.126.com");
//验证 (Credentials 凭证)
Client.Credentials = new System.Net.NetworkCredential("你邮箱的地址", "你登陆邮箱的密码");
//处理待发的电子邮件的方法 (Delivery 发送,传输)
Client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
Client.Send(Email);
Response.Write("已发送成功啦");
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
Client.Send(Email );
}
else
{
Response.Write("Failed to deliver message to {0}"+ex.FailedRecipient[i].ToString().Trim()+"
");
}
}
请注意,上述的代码绝对没有任何问题。但是,使用最近才注册的126邮箱进行发送,是绝对不成功的,但是,使用2002年左右注册的126邮箱发送,是一定成功的,这不知道什么原因,偶对比了注册已久的邮箱和最近注册的邮箱,才发现这个问题的,网上很多人都说无法发送,我也遇到过,但是我使用N年前注册的邮箱,发送就能成功。