在.net2005中,利用System.Net.Mail;下的MailMessage类发送邮件,为了防止附件文件名中的中文字符变成乱码,需要加attachment.NameEncoding = Encoding.GetEncoding("GB2312");详细见下面的函数:
private bool SendMail(string strFrom, string strTo, string strSubject, string strBody, bool isBodyHtml, string strFileName, string strSenderName, string strPassword, string strMailServer)
{
bool success = false;
MailAddress from = new MailAddress(strFrom);
MailAddress to = new MailAddress(strTo);
MailMessage msg = new MailMessage(from, to);
msg.Subject = strSubject;
msg.Body = strBody;
msg.IsBodyHtml = isBodyHtml;
if (strFileName != "")
{
Attachment attachment = new Attachment(strFileName);
attachment.NameEncoding = Encoding.GetEncoding("GB2312");
msg.Attachments.Add(attachment);
}
try
{
SmtpClient client = new SmtpClient(strMailServer);
client.Credentials = new System.Net.NetworkCredential(strSenderName, strPassword);
client.Send(msg);
Response.Write("<font color=blue>Success:</font> Send to /"<b>" + strTo + "</b>/"<br />");
success = true;
}
catch(Exception ex)
{
Response.Write("<font color=red>Fail:</font> Send to /"<b>" + strTo + "</b>/"" + ex.Message +"<br />");
success = false;
}
return success;
}