c# SendMail发送邮件实例代码
using system;
using system.collections.generic;
using system.net;
using system.net.mail;
using system.text;
namespace common
{
/// <summary>
/// 基于system.net.mail发送邮件,支持附件
/// </summary>
public class netsendmail
{
public static void mailsend(string mailfrom, string maifromlaccount, string mailfrompwd, string mailsmtpserver, ilist<string> mailto, ilist<string> mailcc, ilist<string> mailbcc, string mailtitle, string mailcontent, ilist<string> mailattachments, system.text.encoding encoding, bool isbodyhtml)
{
mailmessage message = new mailmessage();
if (mailfrom.trim() == "")
{
throw new exception("发送邮件不可以为空");
}
message.from = new mailaddress(mailfrom);
if (mailto.count <= 0)
{
throw new exception("接收邮件不可以为空");
}
foreach (string s in mailto)
{
message.to.add(new mailaddress(s));
}
if (mailcc.count > 0)
{
foreach (string s in mailcc)
{
message.cc.add(new mailaddress(s));
}
}
if (mailbcc.count > 0)
{
foreach (string s in mailbcc)
{
message.bcc.add(new mailaddress(s));
}
}
message.subject = mailtitle;
message.body = mailcontent;
message.bodyencoding = encoding; //邮件编码
message.isbodyhtml = isbodyhtml; //内容格式是否是html
message.priority = mailpriority.high; //设置发送的优先集
//附件
foreach (string att in mailattachments)
{
message.attachments.add(new attachment(att));
}
smtpclient smtpclient = new smtpclient();
smtpclient.host = mailsmtpserver;
smtpclient.credentials = new networkcredential(maifromlaccount, mailfrompwd);
smtpclient.timeout = 1000;
smtpclient.enablessl = false; //不使用ssl连接
smtpclient.send(message);
}
public static void mailsendtext(string mailfrom, string maifromlaccount, string mailfrompwd, string mailsmtpserver, ilist<string> mailto, ilist<string> mailcc, ilist<string> mailbcc, string mailtitle, string mailcontent)
{
list<string> attlist = new list<string>();
mailsend(mailfrom, maifromlaccount, mailfrompwd, mailsmtpserver, mailto, mailcc, mailbcc, mailtitle, mailcontent, attlist, encoding.utf8, false);
}
public static void mailsendhtml(string mailfrom, string maifromlaccount, string mailfrompwd, string mailsmtpserver, ilist<string> mailto, ilist<string> mailcc, ilist<string> mailbcc, string mailtitle, string mailcontent)
{
list<string> attlist = new list<string>();
mailsend(mailfrom, maifromlaccount, mailfrompwd, mailsmtpserver, mailto, mailcc, mailbcc, mailtitle, mailcontent, attlist, encoding.utf8, true);
}
}
}