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);
}
/// <summary>
/// C#發送郵件函數
/// </summary>
/// <param name="from">寄件者郵箱</param>
/// <param name="fromer">發送人</param>
/// <param name="to">接受者郵箱</param>
/// <param name="toer">收件者</param>
/// <param name="Subject">主題</param>
/// <param name="Body">內容</param>
/// <param name="file">附件</param>
/// <param name="SMTPHost">smtp伺服器</param>
/// <param name="SMTPuser">郵箱</param>
/// <param name="SMTPpass">密碼</param>
/// <returns></returns>
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();
}
}