C#發(fā)送郵件及附件
C#發(fā)送郵件的功能在網(wǎng)上找了很多也有利用socket的 ,試了一下不行的原因是smtp服務(wù)器的問題。在這里我用了mailmessage和搜狐的stmp.sohu.com。源碼如下:
protected void Button1_Click(object sender, EventArgs e)
{
string from = ******@sohu.com;
string fromer = "發(fā)件人";
string to = "*****@126.com";
string toer = "收件人";
string Subject = "郵件標(biāo)題";
string file="附件地址";
string Body ="發(fā)送內(nèi)容";
string SMTPHost = "smtp.sohu.com";
string SMTPuser = "******@sohu.com";
string SMTPpass = "*******";
sendmail(from, fromer, to, toer, Subject, Body,file,SMTPHost, SMTPuser, SMTPpass);
}
/// <summary>
/// C#發(fā)送郵件函數(shù)
/// </summary>
/// <param name="from">發(fā)送者郵箱</param>
/// <param name="fromer">發(fā)送人</param>
/// <param name="to">接受者郵箱</param>
/// <param name="toer">收件人</param>
/// <param name="Subject">主題</param>
/// <param name="Body">內(nèi)容</param>
/// <param name="file">附件</param>
/// <param name="SMTPHost">smtp服務(wù)器</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)
{
////設(shè)置from和to地址
MailAddress from = new MailAddress(sfrom, sfromer);
MailAddress to = new MailAddress(sto, stoer);
////創(chuàng)建一個(gè)MailMessage對象
MailMessage oMail = new MailMessage(from, to);
//// 添加附件
if (sfile != "")
{
oMail.Attachments.Add(new Attachment(sfile));
}
////郵件標(biāo)題
oMail.Subject = sSubject;
////郵件內(nèi)容
oMail.Body = sBody;
////郵件格式
oMail.IsBodyHtml = false;
////郵件采用的編碼
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
////設(shè)置郵件的優(yōu)先級為高
oMail.Priority = MailPriority.High;
////發(fā)送郵件
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();
}
}

浙公網(wǎng)安備 33010602011771號