c# 发送邮件

在命名空间using System.Net.Mail中提供方法根据指定的smtp服务器来发送邮件。下面说说如何实现:

1、首先要发送邮件,需要有一个邮箱帐号,比如网易邮箱、新郎邮箱、qq邮箱等,我以网易的163邮箱为例。然后我们需要知道163邮箱的smtp服务器地址:smtp.163.com。一般常用的Smtp服务器地址为:网易126:smtp.126.com网易163:smtp.163.com搜狐:smtp.sohu.com新浪:smtp.sina.com.cn雅虎:smtp.mail.yahoo.com

2、现在我们可以开始实现了。在新建的C# Console Application中,需要加入两个命名空间:

using System.Net.Mail; //新建邮件、发送邮件需要用到using System.Net; //建立认证帐号需要用到

3、下面是发送邮件的函数:

string userPswd, //邮箱帐号密码string toEmail, //收件人邮箱string mailServer, //邮件服务器string subject, //邮件标题string mailBody, //邮件内容

string[] attachFiles //邮件附件

)

{

//邮箱帐号的登录名

string username = userEmail.Substring(0, userEmail.IndexOf('@'));

//邮件发送者

MailAddress from = new MailAddress(userEmail);

//邮件接收者

MailAddress to = new MailAddress(toEmail);

MailMessage mailobj = new MailMessage(from, to);

//添加发送和抄送

// mailobj.To.Add(""); // mailobj.CC.Add("");

//邮件标题

mailobj.Subject = subject;

//邮件内容

mailobj.Body = mailBody;

foreach (string attach in attachFiles)

{

mailobj.Attachments.Add(new Attachment(attach));

}

//邮件不是html格式

mailobj.IsBodyHtml = false;

//邮件编码格式

mailobj.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");

//邮件优先级

mailobj.Priority = MailPriority.High;

//Initializes a new instance of the System.Net.Mail.SmtpClient class //that sends e-mail by using the specified SMTP server.

SmtpClient smtp = new SmtpClient(mailServer);

//或者用:

//SmtpClient smtp = new SmtpClient();

//smtp.Host = mailServer;

//不使用默认凭据访问服务器

smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(username, userPswd);

//使用network发送到smtp服务器

smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

try

{

//开始发送邮件

smtp.Send(mailobj);

}

catch (Exception e)

{

Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace);

}

}

4、好了,你也可以去试试给自己的应用程序加上发送邮件的功能了。

转载自:http://hi.baidu.com/wangcaidpj219x/blog/item/3b03d72526b2043bd40742b6.html

原文地址:https://www.cnblogs.com/nianyuwen/p/2536641.html