C#发送邮件的功能在网上找了很多也有利用socket的 ,试了一下不行的原因是smtp服务器的问题。在这里我用了mailmessage和搜狐的stmp.sohu.com。源码如下:
protected void Button1_Click(object sender, EventArgs e)
{
string from = ******@sohu.com;
string fromer = "发件人";
string to = "*****@126.com";
string toer = "收件人";
string Subject = "邮件标题";
string file="附件地址";
string Body ="发送内容";
string SMTPHost = "smtp.sohu.com";
string SMTPuser = "******@sohu.com";
string SMTPpass = "*******";
sendmail(from, fromer, to, toer, Subject, Body,file,SMTPHost, SMTPuser, SMTPpass);
}
///
/// C#发送邮件函数
///
/// 发送者邮箱
/// 发送人
/// 接受者邮箱
/// 收件人
/// 主题
/// 内容
/// 附件
/// smtp服务器
/// 邮箱
/// 密码
///
public bool sendmail(string sfrom, string sfromer, string sto, string stoer, string sSubject, string sBody, string sfile, string sSMTPHost, string sSMTPuser, string sSMTPpass)
{
////设置from和to地址
MailAddress from = new MailAddress(sfrom, sfromer);
MailAddress to = new MailAddress(sto, stoer);
////创建一个MailMessage对象
MailMessage oMail = new MailMessage(from, to);
//// 添加附件
if (sfile != "")
{
oMail.Attachments.Add(new Attachment(sfile));
}
////邮件标题
oMail.Subject = sSubject;
////邮件内容
oMail.Body = sBody;
////邮件格式
oMail.IsBodyHtml = false;
////邮件采用的编码
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
////设置邮件的优先级为高
oMail.Priority = MailPriority.High;
////发送邮件
SmtpClient client = new SmtpClient();
////client.UseDefaultCredentials = false;
client.Host = sSMTPHost;
client.Credentials = new NetworkCredential(sSMTPuser, sSMTPpass);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(oMail);
return true;
}
catch (Exception err)
{
Response.Write(err.Message.ToString());
return false;
}
finally
{
////释放资源
oMail.Dispose();
}
}