.NET常用方法——邮件发送

邮件发送类文件,可直接使用;

调用方法(实例化、静态调用):

实例化:

string exception = "";

SendEmail.SendEmail SE = new SendEmail.SendEmail("aaa@163.com", "aaa", "smtp.163.com", "管理员");

SE.SendMails("aaa<aaa@qq.com>;aaa<aaa@hotmail.com>;", "你好", "您好!", new string[] { }, out exception);

静态使用

SendEmail.SendEmail.Sends("aaa@163.com", "aaa", "aaa", TextBox1.Text, TextBox2.Text, TextBox3.Text, "smtp.163.com", true, FilePaths, out exception);

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions; namespace SendEmail
{
public class SendEmail
{
/// <summary>
/// 发送者邮箱地址
/// </summary>
private static string fromMailAddress;
/// <summary>
/// 发送者邮箱密码
/// </summary>
private static string fromMailPwd;
/// <summary>
/// 发送者邮箱SMTP
/// </summary>
private static string fromMailSMTP;
/// <summary>
/// 发送者邮箱显示名称
/// </summary>
private static string fromDisplayName; /// <summary>
/// 构造基础参数
/// </summary>
/// <param name="frommailaddress">发送方邮箱地址</param>
/// <param name="frommailpwd">发送方邮箱密码</param>
/// <param name="frommailsmtp">发送方smtp地址</param>
/// <param name="fromdisplayname">发送者邮箱显示名称</param>
public SendEmail(string frommailaddress, string frommailpwd, string frommailsmtp, string fromdisplayname)
{
fromMailAddress = frommailaddress;
fromMailPwd = frommailpwd;
fromMailSMTP = frommailsmtp;
fromDisplayName = fromdisplayname;
} public SendEmail()
{
XmlDocument doc = new XmlDocument();
doc.Load(System.Web.HttpContext.Current.Server.MapPath("~/SystemConfig.xml"));
XmlNode ServerMail = doc.SelectSingleNode("/Condition/System/ServerMail");
XmlNode PwdMail = doc.SelectSingleNode("/Condition/System/PwdMail");
XmlNode SMTP = doc.SelectSingleNode("/Condition/System/SMTP");
XmlNode DisplayName = doc.SelectSingleNode("/Condition/System/DisplayName");
if (ServerMail != null && ServerMail.InnerText != "" && PwdMail != null && PwdMail.InnerText != "" && SMTP != null && SMTP.InnerText != "" && DisplayName != null && DisplayName.InnerText != "")
{
fromMailAddress = ServerMail.InnerText;
fromMailPwd =  Encoding.Default.GetString(Convert.FromBase64String(doc.SelectSingleNode("/Condition/System/PwdMail").InnerText));
fromMailSMTP = SMTP.InnerText;
fromDisplayName = DisplayName.InnerText;
}
} /// <summary>
/// 实例化后邮件发送
/// </summary>
/// <param name="ToEmails">接收邮件地址,lzy <lo_yung@163.com>;</param>
/// <param name="eSubject">邮件标题</param>
/// <param name="eBody">邮件内容</param>
/// <param name="FileNames">邮件附件,无附件为null</param>
/// <param name="exception">未发送成功异常消息</param>
/// <returns>是否发送成功</returns>
public bool SendMails(string ToEmails, string eSubject, string eBody, string[] FileNames, out string exception)
{
bool Result = false;
//实例化发送内容对象
MailMessage oMail = new MailMessage();//创建一个MailMessage对象
try
{
MailAddress from = new MailAddress(fromMailAddress, fromDisplayName);//设置发送者信息
oMail.From = from;//设置发信人地址
oMail.Subject = eSubject;//邮件标题
oMail.Body = eBody; //邮件内容
oMail.IsBodyHtml = true; //指定邮件格式,支持HTML格式
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//邮件采用的编码,字符集,缺省为"US-ASCII"
oMail.Priority = MailPriority.High;//设置邮件的优先级为高
oMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;//发送结果通知
if (FileNames.Length > )
{
foreach (string filepath in FileNames)
oMail.Attachments.Add(new Attachment(filepath));//邮件添加附件
} //实例化发送载体
SmtpClient client = new SmtpClient(); //实例化发送邮件SMTP服务器
client.Host = fromMailSMTP; //指定邮件服务器
client.UseDefaultCredentials = false;//凭据是否随请求一起发送,必须放在client.Credentials前
client.Credentials = new NetworkCredential(fromMailAddress, fromMailPwd);//指定服务器邮件,及密码
client.DeliveryMethod = SmtpDeliveryMethod.Network;//将邮件内容发送到SMTP服务器发出
//接收邮件格式化
if (ToEmails.Trim().IndexOf(";") != - && ToEmails.Trim().IndexOf("<") != - && ToEmails.Trim().IndexOf(">") != -)
{
string[] mailNames = ToEmails.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in mailNames)
{
if (!string.IsNullOrEmpty(name))
{
string displayName = ""; string address = "";
//邮件格式loyung <lo_yung@163.com>;
if (name.IndexOf('<') > )
{
displayName = name.Substring(, name.IndexOf('<'));
address = name.Substring(name.IndexOf('<') + ).Replace('>', ' ');
}
oMail.To.Add(new MailAddress(address, displayName));
}
}
}
else
{
Regex reg = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$");
if (reg.IsMatch(ToEmails.Trim()))
{
oMail.To.Add(new MailAddress(ToEmails.Trim(), ToEmails.Trim().Substring(, ToEmails.Trim().IndexOf("@"))));
}
else
{
exception = "邮箱格式不正确";
Result = false;
}
}
client.Send(oMail); //发送邮件
exception = "发送成功!";
Result = true;
}
catch (Exception ex)
{
exception = ex.Message;
Result = false;
}
finally
{
oMail.Dispose(); //释放资源
}
return Result;
} /// <summary>
/// 静态方法,发送邮件
/// </summary>
/// <param name="FromEmailAddress">发送方邮箱地址</param>
/// <param name="FromDisplayName">发送方邮箱显示名称</param>
/// <param name="FromPWD">发送方邮箱密码</param>
/// <param name="ToEmails">接收邮件地址,lzy <lo_yung@163.com>;</param>
/// <param name="eSubject">邮件标题</param>
/// <param name="eBody">邮件内容</param>
/// <param name="SMTP">发送方smtp地址</param>
/// <param name="IsBodyHtml">邮件内容是否以html呈现</param>
/// <param name="FileNames">邮件附件,无附件为null</param>
/// <param name="exception">未发送成功异常消息</param>
/// <returns>是否发送成功</returns>
public static bool Sends(string FromEmailAddress, string FromDisplayName, string FromPWD, string ToEmails, string eSubject, string eBody, string SMTP, bool IsBodyHtml, string[] FileNames, out string exception)
{
bool Result = false;
//实例化发送内容对象
MailMessage oMail = new MailMessage();//创建一个MailMessage对象
try
{
MailAddress from = new MailAddress(FromEmailAddress, FromDisplayName);//设置发送者信息
oMail.From = from;//设置发信人地址
oMail.Subject = eSubject;//邮件标题
oMail.Body = eBody; //邮件内容
oMail.IsBodyHtml = true; //指定邮件格式,支持HTML格式
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//邮件采用的编码,字符集,缺省为"US-ASCII"
oMail.Priority = MailPriority.High;//设置邮件的优先级为高
oMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;//发送结果通知
if (FileNames.Length > )
{
foreach (string filepath in FileNames)
oMail.Attachments.Add(new Attachment(filepath));//邮件添加附件
} //实例化发送载体
SmtpClient client = new SmtpClient(); //实例化发送邮件SMTP服务器
client.Host = SMTP; //指定邮件服务器
client.UseDefaultCredentials = false;//凭据是否随请求一起发送,必须放在client.Credentials前
client.Credentials = new NetworkCredential(FromEmailAddress, FromPWD);//指定服务器邮件,及密码
client.DeliveryMethod = SmtpDeliveryMethod.Network;//将邮件内容发送到SMTP服务器发出
//接收邮件格式化
if (ToEmails.Trim().IndexOf(";") != - && ToEmails.Trim().IndexOf("<") != - && ToEmails.Trim().IndexOf(">") != -)
{
string[] mailNames = ToEmails.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in mailNames)
{
if (!string.IsNullOrEmpty(name))
{
string displayName = ""; string address = "";
//邮件格式loyung <lo_yung@163.com>;
if (name.IndexOf('<') > )
{
displayName = name.Substring(, name.IndexOf('<'));
address = name.Substring(name.IndexOf('<') + ).Replace('>', ' ');
}
oMail.To.Add(new MailAddress(address, displayName));
}
}
}
else
{
Regex reg = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$");
if (reg.IsMatch(ToEmails.Trim()))
{
oMail.To.Add(new MailAddress(ToEmails.Trim(), ToEmails.Trim().Substring(, ToEmails.Trim().IndexOf("@"))));
}
else
{
exception = "邮箱格式不正确";
Result = false;
}
}
client.Send(oMail); //发送邮件
exception = "发送成功!";
Result = true;
}
catch (Exception ex)
{
exception = ex.Message;
Result = false;
}
finally
{
oMail.Dispose(); //释放资源
}
return Result;
} }
}
上一篇:3.CSS字体属性


下一篇:关于form.submit()不能提交表单的错误原因