使用Net.Mail、CDO组件、JMail组件三种方式发送邮件

原文:使用Net.Mail、CDO组件、JMail组件三种方式发送邮件

一、使用Net.Mail

需要服务器认证,大部分服务器端口为25.

         /// <summary>
/// 用MailMessage通过需要认证的SMTP服务器发送邮件,可以发送附件
/// </summary>
/// <param name="frmAddress">发件箱地址,例:myaccount@163.com</param>
/// <param name="password">发件箱登录密码</param>
/// <param name="toAddress">收件箱地址,多个地址使用";"隔开,例:youraccount@sina.com</param>
/// <param name="copyTo">抄送地址,多个地址使用";"隔开,例:hisaccount@QQ.com</param>
/// <param name="mailSubject">邮件主题,例:MailTest</param>
/// <param name="mailContent">邮件内容,例:Hello</param>
/// <param name="mailserver">发件箱所在的SMTP服务器,例:smtp.163.com</param>
public void NetSendMail(string frmAddress, string password, string toAddress, string copyTo, string mailSubject, string mailContent, string mailserver)
{
///添加发件人地址
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress(frmAddress);
///添加收件人地址
string split = ";";
string[] toList = toAddress.Trim().Split(split.ToCharArray());
for (int i = ; i < toList.Length; i++)
{
mailMsg.To.Add(toList[i].Trim());
}

///添加抄送地址
string[] ccList = copyTo.Trim().Split(split.ToCharArray());
for (int i = ; i < ccList.Length; i++)
{
if (ccList[i].Trim().Length > )
{
mailMsg.CC.Add(ccList[i].Trim());
}
}

///添加邮件主题
mailMsg.Subject = mailSubject.Trim();
mailMsg.SubjectEncoding = Encoding.UTF8;

///添加邮件内容
mailMsg.Body = mailContent;
mailMsg.BodyEncoding = Encoding.UTF8;
mailMsg.IsBodyHtml = true; //正文是否为html样式

///添加邮件附件
HttpFileCollection fileList = HttpContext.Current.Request.Files;
for (int i = ; i < fileList.Count; i++)
{ ///添加单个附件
HttpPostedFile file = fileList[i];
if (file.FileName.Length <= || file.ContentLength <= )
{
break;
}
string path = Server.MapPath("~/FileUpload/"); //附件保存在程序所在的目录FileUpload下
string name = System.IO.Path.GetFileName(file.FileName);
file.SaveAs(path + name);
mailMsg.Attachments.Add(new System.Net.Mail.Attachment(file.FileName));
}
try
{
//实例化SmtpClient邮件发送类对象
SmtpClient client = new SmtpClient(mailserver, ); //大部分smtp服务器的端口是25
//设置用于验证发件人身份的凭据
client.Credentials = new System.Net.NetworkCredential(frmAddress, password);
//发送邮件
client.Send(mailMsg);
Response.Write("<script type='text/javascript'>alert('发送成功!')</script>");
}
catch
{
Response.Write("<script type='text/javascript'>alert('发送失败')</script>");
}
}

二、使用CDO组件

 /// <summary>
/// 用CDO组件通过需要认证的SMTP服务器发送邮件。
/// 添加cdosys.dll引用,可以在系统目录(如c:\winnt或c:\windows)的system32子目录中找到它(cdosys.dll)。
/// </summary>
/// <param name="frmAddress">发件箱地址,例:myaccount@163.com</param>
/// <param name="password">发件箱登录密码</param>
/// <param name="toAddress">收件箱地址,多个地址使用";"隔开,例:youraccount@sina.com</param>
/// <param name="copyTo">抄送地址,多个地址使用";"隔开,例:hisaccount@QQ.com</param>
/// <param name="mailSubject">邮件主题,例:MailTest</param>
/// <param name="mailContent">邮件内容,例:Hello</param>
/// <param name="mailserver">发件箱所在的SMTP服务器,例:smtp.163.com</param>
public void CDOSendMail(string frmAddress, string password, string toAddress, string copyTo, string mailSubject, string mailContent, string mailserver)
{
try
{
CDO.Message oMsg = new CDO.Message();

oMsg.From = frmAddress; //添加发件人

oMsg.To = toAddress; //多人用“;”,“,”分开,自动识别,

oMsg.CC = copyTo;
oMsg.Subject = mailSubject;
oMsg.HTMLBody = "<html><body>" + mailContent + "</body></html>";
CDO.IConfiguration iConfg = oMsg.Configuration;
ADODB.Fields oFields = iConfg.Fields;

oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = ;
oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = frmAddress;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = toAddress;
oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = frmAddress;
oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = password;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = ;
//value=0 代表Anonymous验证方式(不需要验证)
//value=1 代表Basic验证方式(使用basic (clear-text) authentication.
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.)
//Value=2 代表NTLM验证方式(Secure Password Authentication in Microsoft Outlook Express)
oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value = 0x0804;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = mailserver;

oFields.Update();
oMsg.BodyPart.Charset = "gb2312";
oMsg.HTMLBodyPart.Charset = "gb2312";


//添加邮件附件
HttpFileCollection fileList = HttpContext.Current.Request.Files;
for (int i = ; i < fileList.Count; i++)
{ ///添加单个附件
HttpPostedFile file = fileList[i];
if (file.FileName.Length <= || file.ContentLength <= )
{
break;
}
string path = Server.MapPath("~/FileUpload/"); //附件保存在程序所在的目录FileUpload下
string name = System.IO.Path.GetFileName(file.FileName);
file.SaveAs(path + name);
oMsg.AddAttachment(file.FileName);
}

oMsg.Send();
oMsg = null;
}
catch (Exception e)
{
throw e;
}
}

三、使用JMail组件

         /// <summary>
/// 用JMail组件发送邮件。
/// 添加jmail.dll引用
/// </summary>
/// <param name="frmAddress">发件箱地址,例:myaccount@163.com</param>
/// <param name="password">发件箱登录密码</param>
/// <param name="toAddress">收件箱地址,多个地址使用";"隔开,例:youraccount@sina.com</param>
/// <param name="copyTo">抄送地址,多个地址使用";"隔开,例:hisaccount@QQ.com</param>
/// <param name="mailSubject">邮件主题,例:MailTest</param>
/// <param name="mailContent">邮件内容,例:Hello</param>
/// <param name="mailserver">发件箱所在的SMTP服务器,例:smtp.163.com</param>
public bool JMailSendMail(string frmAddress, string password, string toAddress, string copyTo, string mailSubject, string mailContent, string mailserver)
{
try
{
MessageClass jmMessage = new MessageClass();
jmMessage.Charset = "gb2312";
jmMessage.ISOEncodeHeaders = false; //信头编码iso-8859-1字符集
jmMessage.Encoding = "base64"; //附件的编码格式
//jmMessage.ContentType = "text/html"; //正文类型,去掉,否则正文出现乱码

jmMessage.MailServerUserName = frmAddress; //发件箱登录名
jmMessage.MailServerPassWord = password; //发件箱密码

jmMessage.From = frmAddress; //发件箱

jmMessage.Subject = mailSubject;
jmMessage.Body = mailContent;

//回执,当对方阅读了邮件后提醒是否发送回执
jmMessage.ReturnReceipt = true;
jmMessage.AddNativeHeader("Disposition-Notification-To", frmAddress);//回执接受人的邮件地址

//收件箱
string split = ";";
string[] toList = toAddress.Trim().Split(split.ToCharArray());
for (int i = ; i < toList.Length; i++)
{
jmMessage.AddRecipient(toList[i].Trim(), "", "");
}

//抄送
string[] coList = copyTo.Trim().Split(split.ToCharArray());
for (int i = ; i < coList.Length; i++)
{
jmMessage.AddRecipientCC(coList[i].Trim(), "", "");
}

///添加邮件附件
HttpFileCollection fileList = HttpContext.Current.Request.Files;
for (int i = ; i < fileList.Count; i++)
{ ///添加单个附件
HttpPostedFile file = fileList[i];
if (file.FileName.Length <= || file.ContentLength <= )
{
break;
}
string path = Server.MapPath("~/FileUpload/"); //附件保存在程序所在的目录FileUpload下
string name=System.IO.Path.GetFileName(file.FileName);
file.SaveAs(path + name);
jmMessage.AddAttachment(file.FileName);
}

if (jmMessage.Send(mailserver, false))
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{

throw;
}
}

对于JMail组件,通常我们遇到的错误是:'The message was undeliverable. All servers failed to receive the message ',这其实是JMAIL返回的错误,并不是ASP代码产生的,根本原因是MAIL SERVER拒绝了JMAIL的请求.

  究其原因,是那些服务器不提供SMTP服务或者没有开启smtp服务;或是在服务器端开启了'禁止邮件中继服务'选项,也就是说不在其允许的IP段或指定范围内的空间里的程序是无法使用其SMTP服务的。解决方案:使用支持smtp的邮件服务器. 使用支持外来jmail申请验证身份,发送邮件的邮件服务器。 最好:使用自己的待遇smtp功能的企业邮局。因为外面的免费的邮局可能会有一些特殊设置,不如防止垃圾邮件,防止盗用邮件身份等等!

Jmail发送首先要通过邮件服务器验证。如果你的服务器不支持SMTP或者你的账号不能使用SMTP服务那么就无法发送。163以前的用户默认是开通POP和SMTP服务的,但新用户都不开通,需要付费才能使用。要想确定某一邮箱是否可以使用POP和SMTP,你可以用foxmail等邮件软件看能否收取该邮箱信件。

目前发现可以通过的stmp服务器有:smtp.qq.com、smtp.163.com,也就是说可以使用该类的邮箱给其他邮箱发送邮件。

上一篇:【C语言】11-指针


下一篇:java小提示:标示符常见命名规则、常用ASCII