您的位置:首页 > 编程语言 > C#

C#原生邮件发送+发送日志记录

2011-10-10 17:17 309 查看
首先需要两个引用:

using System.Net.Mail;
using System.IO;


以下为正文:

public int sendMail(string from, string to, string subject, string body, string host, string username, string password)
{
try
{
int n=0;

MailAddress fromAdd = new MailAddress(from);
MailMessage mail = new MailMessage();

mail.Subject = subject;
mail.From = new MailAddress(from);
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
client.Host = host;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(username, password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;

string[] toAdd = to.Split(';');

foreach (string temp in toAdd)
{
mail.To.Add(new MailAddress(temp));
client.Send(mail);
mail.To.Clear();
n++;
WriteInfo("发送成功:"+temp);
}

return n;
}
catch (Exception ex)
{
throw ex;
}
}

public void WriteInfo(string errorMessage)
{
try
{
//string pathInfo = ConfigurationManager.AppSettings["ErrorsIn"];
//string ErrorTxtPath = pathInfo.ToString().Trim() + "" + DateTime.Now.ToString("yyyyMMdd") + ".txt";

Directory.CreateDirectory("Log");//创建文件夹
string ErrorTxtPath = "Log" + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!File.Exists(ErrorTxtPath))
{

using (FileStream fs = File.Create(ErrorTxtPath))
{
}

}
StreamWriter writerInfo = new StreamWriter(ErrorTxtPath, true);
string errInfo = DateTime.Now.ToString() + ":工作邮件发送日志:" + errorMessage + "\r\n  ";
writerInfo.Write(errInfo);
writerInfo.Close();

}
catch
{

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐