前些天在.NET的QQ群里面,有人提到ASP.NET发邮件的问题,现在整了个类,测试通过后发布出来,供大家切磋交流使用完善等.
SMTP发邮件的类
=======================
using System;
using System.Web.Mail;
using System.ServiceProcess;
using System.Collections;
namespace MailTest
{
/// <summary>
/// MailClass 的摘要说明。
/// </summary>
public class MailClass
{
string strFrom;
string strTo;
string strCC;
string strBcc;
string strSubject;
string strBody;
string strPriority;
string strBodyFormat;
public MailClass()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public string MailFrom
{
get
{
return strFrom;
}
set
{
strFrom = value;
}
}
public string MailTo
{
get
{
return strTo;
}
set
{
strTo = value;
}
}
public string MailCC
{
get
{
return strCC;
}
set
{
strCC = value;
}
}
public string MailBcc
{
get
{
return strBcc;
}
set
{
strBcc = value;
}
}
public string MailSubject
{
get
{
return strSubject;
}
set
{
strSubject = value;
}
}
public string MailPriority
{
get
{
return strPriority;
}
set
{
strPriority = value;
}
}
public string MailBody
{
get
{
return strBody;
}
set
{
strBody = value;
}
}
public string MailBodyFormat
{
get
{
return strBodyFormat;
}
set
{
strBodyFormat = value;
}
}
public string SendMail()
{
string strResult="";
MailMessage mailMsg = new MailMessage();
mailMsg.From = strFrom;
mailMsg.To = strTo;
mailMsg.Cc = strCC;
mailMsg.Bcc = strBcc;
mailMsg.Subject = strSubject;
mailMsg.Body = strBody;
// mailMsg.Priority = (MailPriority) strPriority;
// mailMsg.BodyFormat = (MailFormat)strBodyFormat;
if (strBodyFormat.Equals("Html")) mailMsg.BodyFormat = MailFormat.Html;
else mailMsg.BodyFormat = MailFormat.Text;
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "user");
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "Psw");
ServiceController[] services = ServiceController.GetServices();
bool blnHasSmtpService = false;
ServiceController smtpServ = null;
foreach(ServiceController service in services)
{
if (service.ServiceName.ToLower() == "smtpsvc")
{
blnHasSmtpService = true;
smtpServ = service;
break;
}
}
if (!blnHasSmtpService)
{
strResult ="You do not have SMTP Service installed on this " +
"machine. Please check the Readme file for information on how " +
"to install SMTP Service.";
}
// Ensure the SMTP Service is running. if not, start it.
if (smtpServ != null)
{
if (smtpServ.Status != ServiceControllerStatus.Running)
{
try
{
smtpServ.Start();
}
catch (Exception ex)
{
strResult ="There was an error when attempting to start SMTP Service. more information."+ex.Message;
}
}
SmtpMail.SmtpServer = "smtp.163.com";
try
{
SmtpMail.Send(mailMsg);
strResult ="Your email has been successfully sent!";
}
catch( Exception exp)
{
strResult ="The following problem occurred when attempting to send your email: " + exp.Message;
//如果报告 未能访问CDO.message对象 的错误,请考虑是否防火墙阻挡 25端口需要开放
}
}
return strResult ;
}
}
}
浙公网安备 33010602011771号