我相信这对于使用过C#发邮件的过来人来说,太不屑一顾了,呵呵,我是第一次发现原来我也能写blog的地方,所以急手之急,就随便弄出些文字看看效果再说的哟,
但对于初次使用C#发邮件应该还是有一点帮助的.
费话少说了,看看下面的代码对你有用否?
class SendMailer
{
public static void Send(
string subject,
string body,
MailAttachment[] attach)
{
/*
之所以写成Config.* 的原因我想是这些一般都是写到配置文件中的
当然你觉得你不会这样的话,可自行修改的
*/
// MAIL服务器名称或IP都行(比如:smtp.sohu.com)
string server = Config.GetMailServer();
// 接收者邮箱 (比如:XXX@sohu.com),这里当然也可以是多个,以;来分开
string to = Config.GetRecieveAccount();
// 同时暗送给那些接受者
string cc = Config.GetOtherRecieveAccount();
// 注册的帐号 (比如:XXX@sohu.com)
string from = Config.GetSendMailAccount();
// 帐号密码
string pwd = Config.GetSendMailAccountPwd();
MailMessage mail = new MailMessage();
mail.From = from;
mail.To = to;
mail.Subject = subject;
mail.Cc = cc;
mail.Body = body;
mail.Priority = MailPriority.High;
// 粘付件
if (attach != null)
{
for (int i = 0; i < attach.Length; ++i)
{
mail.Attachments.Add(attach[i]);
}
}
SmtpMail.SmtpServer = server;
string user = "";
// 取得帐号ID
Regex r = new Regex("(?<account>.*?)@.*");
Match m = r.Match(from);
if (m != null)
{
user = m.Result("${account}");
}
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", user);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pwd);
try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
}
当然记得要引用相应的命名空间的
using System.Text.RegularExpressions;
using System.Web.Mail;
你是不是说没有此命名空间,别告诉我你不会在VS中添加引用的哟
好了不罗锁了,下班了,回家了.
但对于初次使用C#发邮件应该还是有一点帮助的.
费话少说了,看看下面的代码对你有用否?
class SendMailer
{
public static void Send(
string subject,
string body,
MailAttachment[] attach)
{
/*
之所以写成Config.* 的原因我想是这些一般都是写到配置文件中的
当然你觉得你不会这样的话,可自行修改的
*/
// MAIL服务器名称或IP都行(比如:smtp.sohu.com)
string server = Config.GetMailServer();
// 接收者邮箱 (比如:XXX@sohu.com),这里当然也可以是多个,以;来分开
string to = Config.GetRecieveAccount();
// 同时暗送给那些接受者
string cc = Config.GetOtherRecieveAccount();
// 注册的帐号 (比如:XXX@sohu.com)
string from = Config.GetSendMailAccount();
// 帐号密码
string pwd = Config.GetSendMailAccountPwd();
MailMessage mail = new MailMessage();
mail.From = from;
mail.To = to;
mail.Subject = subject;
mail.Cc = cc;
mail.Body = body;
mail.Priority = MailPriority.High;
// 粘付件
if (attach != null)
{
for (int i = 0; i < attach.Length; ++i)
{
mail.Attachments.Add(attach[i]);
}
}
SmtpMail.SmtpServer = server;
string user = "";
// 取得帐号ID
Regex r = new Regex("(?<account>.*?)@.*");
Match m = r.Match(from);
if (m != null)
{
user = m.Result("${account}");
}
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", user);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pwd);
try
{
SmtpMail.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
}
当然记得要引用相应的命名空间的
using System.Text.RegularExpressions;
using System.Web.Mail;
你是不是说没有此命名空间,别告诉我你不会在VS中添加引用的哟
好了不罗锁了,下班了,回家了.