.NET发送邮件的方法

时间:2021-03-17 14:59:12

整理一下,在.NET中发送邮件的一个方法,代码如下:

 public static string Net_Email(string strSendto, string strCC, string strBCC, string strMailContent, string strMailTitle, string[] strMailAttachMent, string strMailFormat, string strServiceTeam)
{
try
{
MailMessage mMail = new MailMessage();
using (mMail)
{
strMailContent = strMailContent.Replace("<br>\n", "<br>");
string[] ListTo = strSendto.Split(';');
for (int i = ; i < ListTo.Length; i++)
{
if (ListTo[i].Equals("")) continue;
mMail.To.Add(ListTo[i]);
}
string[] ListCC = strCC.Split(';');
for (int i = ; i < ListCC.Length; i++)
{
if (ListCC[i].Equals("")) continue;
mMail.CC.Add(ListCC[i]);
}
string[] ListBCC = strBCC.Split(';');
for (int i = ; i < ListBCC.Length; i++)
{
if (ListBCC[i].Equals("")) continue;
mMail.Bcc.Add(ListBCC[i]);
}
string[] strMailFrom = strServiceTeam.Split(';');
mMail.From = strMailFrom[].IndexOf("@", StringComparison.Ordinal) > ? new MailAddress(strMailFrom[]) : new MailAddress("xxxxx@xxx.com.cn");
mMail.Body = strMailContent;
mMail.Subject = strMailTitle;
mMail.IsBodyHtml = strMailFormat == "";
for (int i = ; i < strMailAttachMent.Length; i++)
{
string strFJ = strMailAttachMent[i] + "";
if (strFJ.Length > )
{
mMail.Attachments.Add(new Attachment(strFJ));
}
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "10.10.10.10";
smtp.Credentials = new NetworkCredential("emailcn", "");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mMail);
return "";
}
}
catch (Exception ex)
{
return ex.Message;
}
}

调用方式:

组装邮件内容的时候,是调用一个html模板,将其中的标签内容进行替换

var strFileCn = File.ReadFile(MapPath("order_model.html"), "utf-8");
strFileCn = strFileCn.Replace("#orderid#", orders.orderid);
strFileCn = strFileCn.Replace("#username#", orders.username);

var att = new string[1];
att[0] = "";

Net_Email(strsendto, strcc, "", strFileCn, "商品订购单Order sheet.",att, "", "")