以下是最近在做一个网站时我写的一个asp.net发送邮件的方法,放在类库中,可以随时拿来用.这个方法中,邮件的附件不需要先上传到服务器再发送,而是直接从你选择的路径中拿来发送
/// <summary>
/// 發送edm郵件,可以附加附件
/// </summary>
/// <param name="StrTo">收件人地址</param>
/// <param name="toDisplayName">收件人名稱</param>
/// <param name="strFrom">發件人地址</param>
/// <param name="fromDisplayName">發件人名稱</param>
/// <param name="StrBody">郵件內容</param>
/// <param name="strSubject">郵件主題</param>
/// <param name="path">附件路徑</param>
/// <returns>返回是否發送成功</returns>
public static bool SendEDMEmailBy47Server(string StrTo, string toDisplayName, string strFrom, string fromDisplayName, string StrBody, string strSubject,string path)
{
System.Net.Mail.MailAddress fromEmail = new System.Net.Mail.MailAddress(strFrom, fromDisplayName);//发件人的地址和发件人名称
System.Net.Mail.MailAddress toEmail = new System.Net.Mail.MailAddress(StrTo, toDisplayName);//收件人地址和收件人名称
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromEmail, toEmail);
mail.Body = StrBody;
mail.Subject = strSubject;
mail.IsBodyHtml = true;
mail.BodyEncoding = Encoding.UTF8;
mail.Priority = System.Net.Mail.MailPriority.Normal;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.Host = "...";//这里设置成你的smtp主机名或者ip地址
smtpClient.Port = 25;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential("xxx", "xxx");//你的用户名和密码
//以下是邮件附件部分,path一般是从FileUpload控件中取~
FileInfo fi;
if (path != "")
{
fi = new FileInfo(path);
if (fi.Exists)
{
System.Net.Mail.Attachment firstatt = new System.Net.Mail.Attachment(path, System.Net.Mime.MediaTypeNames.Application.Octet);
System.Net.Mime.ContentDisposition disposion=new System.Net.Mime.ContentDisposition();
disposion.CreationDate=System.IO.File.GetCreationTime(path);
disposion.ModificationDate=System.IO.File.GetLastWriteTime(path);
disposion.ReadDate=System.IO.File.GetLastAccessTime(path);
mail.Attachments.Add(firstatt);
}
}
try
{
smtpClient.Send(mail);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
return true;
}