引用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

EMailHepler类:

public static class EmailHelper
{
/// <summary>
/// C#发送邮件函数
/// </summary>
/// <param name="fromDisplayName">发件邮箱显示名</param>
/// <param name="sto">收件邮箱</param>
/// <param name="sSubject">主题</param>
/// <param name="sBody">内容</param>
/// <param name="sfiles">附件路径,绝对路径</param>
/// <param name="ccto">抄送地址</param>
/// <param name="isBodyHtml">邮件是否支持html格式</param>
/// <returns></returns>
public static bool Sendmail(string fromDisplayName, string sto, string sSubject, string sBody,
string[] sfiles = null, string[] ccto = null, bool isBodyHtml = false)
{
////设置from和to地址
MailAddress from = new MailAddress(EmailSection.Instance.SMTPuser, fromDisplayName);
MailAddress to = new MailAddress(sto); ////创建一个MailMessage对象
MailMessage oMail = new MailMessage(from, to); //// 添加附件
if (sfiles != null)
{
foreach (var item in sfiles)
{
oMail.Attachments.Add(new Attachment(item));
}
} //添加抄送用户
if (ccto != null)
{
foreach (var item in ccto)
{
oMail.CC.Add(new MailAddress(item));
}
}
////邮件标题
oMail.Subject = sSubject; ////邮件内容
oMail.Body = sBody; ////邮件格式
oMail.IsBodyHtml = isBodyHtml; ////邮件采用的编码
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312"); ////设置邮件的优先级为高
oMail.Priority = MailPriority.Normal; ////发送邮件
SmtpClient client = new SmtpClient();
////client.UseDefaultCredentials = false;
client.Host = EmailSection.Instance.SMTPHost;
client.Credentials = new NetworkCredential(EmailSection.Instance.SMTPuser, EmailSection.Instance.SMTPpass);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(oMail);
return true;
}
catch (Exception err)
{
Console.WriteLine(err.Message.ToString());
return false;
}
finally
{
////释放资源
oMail.Dispose();
} }
}
EmailSection配置相关信息:
public class EmailSection : ConfigurationSection
{
private static EmailSection _instance = null; public static EmailSection Instance
{
get
{
if (_instance == null)
{
_instance = (EmailSection)ConfigurationManager.GetSection(typeof(EmailSection).Name);
}
return _instance;
}
}
[ConfigurationProperty("SMTPHost", IsRequired = true)]
public string SMTPHost
{
get
{ return (String)this["SMTPHost"]; }
set
{ this["SMTPHost"] = value; }
}
[ConfigurationProperty("SMTPuser", IsRequired = true)]
public string SMTPuser
{
get
{ return (String)this["SMTPuser"]; }
set
{ this["SMTPuser"] = value; }
}
[ConfigurationProperty("SMTPpass", IsRequired = true)]
public string SMTPpass
{
get
{ return (String)this["SMTPpass"]; }
set
{ this["SMTPpass"] = value; }
}
}

配置文件配置:

<EmailSection SMTPHost = "smtp.exmail.qq.com" SMTPuser = "[email protected]" SMTPpass = "laiyihuo_1"></EmailSection>
 
05-11 18:24