因项目业务需要,需要做一个发送邮件功能,查了下资料,整了整,汇总如下,亲测可用~
QQ邮箱发送邮件
#region 发送邮箱
try
{
MailMessage mail = new MailMessage();
MailAddress from = new MailAddress("发件人邮箱", "工程管理平台", System.Text.Encoding.GetEncoding("GB2312"));//邮件的发件人
mail.From = from;
MailAddress to = new MailAddress("收件人邮箱");//设置邮件的收件人
mail.To.Add(to);
mail.Subject = "收款确认";
string url = "http://wwww.baidu.com";
mail.Body = "您好,有新的待确认收款" + url;
mail.IsBodyHtml = true;//HTML格式,内容可以包含HMTL标签和超链接uuu
mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置邮件的格式
mail.Priority = MailPriority.Normal;//设置邮件的发送级别
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
SmtpClient client = new SmtpClient();//邮件发送服务器
//client.Port = 25; QQ发送邮件不用设置
client.Host = "smtp.qq.com"; //发件人地址所在的服务器SMTP 如网易126邮箱的为smtp.126.com
client.EnableSsl = true;
client.UseDefaultCredentials = false; //设置用于 SMTP 事务的端口,默认的是 25
client.Credentials = new System.Net.NetworkCredential("发件人邮箱", "授权码");//发件人邮箱登陆名和密码(生成的授权码)
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(mail);//发送邮件
MessageShow("发送成功");
Response.Write("<script language='javascript'>alert('发送成功!');</script>");
}
catch (System.Net.Mail.SmtpException ex)
{ MessageShow(ex.Message);
}
}
catch (Exception ex)
{
throw ex;
}
#endregion
效果:
注意
重要引用:
using System.Net.Mail;
其中,使用QQ发送邮件,需要使用授权码而不是QQ密码,授权码具体生成方式可以查看:http://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28
自定义发送邮件
附帮助类的发送邮件方式(推荐此种方式,更灵活)
邮件帮助类
#region 邮件帮助类
/// <summary>
/// 邮件帮助类
/// </summary>
public static class SendMailHelper
{
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="request">邮件内容对象</param>
/// <returns>发送邮件所遇到的异常</returns>
public static string SendMail(MailRequest request)
{
try
{
MailMessage mail = new MailMessage(); if (string.IsNullOrEmpty(request.From))
{
request.From = ConfigurationManager.AppSettings["DefaultMailFrom"];
}
mail.From = new MailAddress(request.From); PaserMailAddress(request.To, mail.To);
PaserMailAddress(request.CC, mail.CC);
PaserMailAddress(request.Bcc, mail.Bcc); mail.Subject = request.Subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = request.Body;
mail.ReplyTo = new MailAddress(request.From);
mail.IsBodyHtml = true; if (request.Attachments != null && request.Attachments.Length > )
{
for (int i = ; i < request.Attachments.Length; i++)
{
Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName); mail.Attachments.Add(mailAttach);
}
} if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SMTPSERVER_Show"]))
{
throw new ApplicationException("邮件服务无效");
} //Smtp Server
SmtpClient mailClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPSERVER_Show"]); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SMTPSERVERPORT"]))
{
//端口号
try
{
mailClient.Port = Int32.Parse(ConfigurationManager.AppSettings["SMTPSERVERPORT"]);
}
catch
{
return "SMTP服务器端口设置错误,端口必须设置为数值型";
}
} if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["MAILUSER_Show"]))
{
mailClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MAILUSER_Show"], ConfigurationManager.AppSettings["MAILUSERPW_Show"]);
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
}
else
{
mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;
} mailClient.Send(mail);
mail.Dispose(); return string.Empty;
}
catch (SmtpFailedRecipientsException e)
{
return e.Message;
}
catch (SmtpFailedRecipientException e)
{
return e.Message;
}
catch (SmtpException e)
{
return e.Message;
}
catch (Exception e)
{
return e.Message;
}
} /// <summary>
/// 解析分解邮件地址
/// </summary>
/// <param name="mailAddress">邮件地址</param>
/// <param name="mailCollection">邮件对象</param>
private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection)
{
if (string.IsNullOrEmpty(mailAddress))
{
return;
} char[] separator = new char[] { ',', ';' };
string[] addressArray = mailAddress.Split(separator); foreach (string address in addressArray)
{
if (address.Trim() == string.Empty)
{
continue;
} mailCollection.Add(new MailAddress(address));
}
} /// <summary>
/// 字节数组转换为流
/// </summary>
/// <param name="byteArray">字节数组</param>
/// <returns>Stream</returns>
private static Stream ByteArrayToStream(byte[] byteArray)
{
MemoryStream mstream = new MemoryStream(byteArray); return mstream;
}
}
#endregion
补充上述帮助类中,还需要添加 MailRequest.cs 类(发送请求相关类) 和 MailRequestAttachments.cs 类(附件类)
MailRequest.cs 类
using System;
using System.Collections.Generic;
using System.Text; namespace SyncAdData.DBHelper
{
/// <summary>
/// 发送邮件请求
/// </summary>
public class MailRequest
{
#region PrivateFields /// <summary>
/// 文件名
/// </summary>
private string _fromField; /// <summary>
/// 返送到
/// </summary>
private string _toField; /// <summary>
/// 抄送
/// </summary>
private string _copyField; /// <summary>
/// 附件
/// </summary>
private string _bccField; /// <summary>
/// 标题
/// </summary>
private string _subjectField; /// <summary>
/// 发送人名
/// </summary>
private string _bodyField; /// <summary>
/// 类容
/// </summary>
private MailRequestAttachments[] _attachmentsField; #endregion /// <summary>
/// 发送人,多个人以分号;间隔
/// </summary>
public string From
{
get
{
return this._fromField;
} set
{
this._fromField = value;
}
} /// <summary>
/// 收件人,多个人以分号;间隔
/// </summary>
public string To
{
get
{
return this._toField;
} set
{
this._toField = value;
}
} /// <summary>
/// 抄送人,多个人以分号;间隔
/// </summary>
public string CC
{
get
{
return this._copyField;
} set
{
this._copyField = value;
}
} /// <summary>
/// 秘密抄送人,多个人以分号;间隔
/// </summary>
public string Bcc
{
get
{
return this._bccField;
} set
{
this._bccField = value;
}
} /// <summary>
/// 主题
/// </summary>
public string Subject
{
get
{
return this._subjectField;
} set
{
this._subjectField = value;
}
} /// <summary>
/// 内容
/// </summary>
public string Body
{
get
{
return this._bodyField;
} set
{
this._bodyField = value;
}
} /// <summary>
/// 附件列表
/// </summary>
public MailRequestAttachments[] Attachments
{
get
{
return this._attachmentsField;
} set
{
this._attachmentsField = value;
}
}
}
}
MailRequestAttachments.cs 类
using System;
using System.Collections.Generic;
using System.Text; namespace SyncAdData.DBHelper
{
/// <summary>
/// 发送邮件请求附件
/// </summary>
public class MailRequestAttachments
{
#region PrivateFields /// <summary>
/// 文件名
/// </summary>
private string _fileNameField; /// <summary>
/// 文件内容
/// </summary>
private byte[] _fileDataField; #endregion /// <summary>
/// 文件名
/// </summary>
public string FileName
{
get
{
return this._fileNameField;
} set
{
this._fileNameField = value;
}
} /// <summary>
/// 文件内容
/// </summary>
public byte[] FileData
{
get
{
return this._fileDataField;
} set
{
this._fileDataField = value;
}
}
}
}
需要的命名空间
using System;
using System.Reflection;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net;
using System.IO;
其中 帮助类中的服务器地址 和 账号 密码需要在配置文件中配置
<add key="SMTPSERVER" value="邮件服务器"/>
<add key="MAILUSER" value="账号"/>
<add key="MAILUSERPW" value="密码"/>
前台调用
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="StrUrl">根据业务需要,这里我需要传入几个拼接后的id值</param>
/// <param name="bid">根据业务需要,这里我传的批次id</param>
/// <param name="showemail">根据业务需要,这里我传入的是查询出来的收件人邮箱(如果是固定的更好,可以直接写死或者写成配置文件)</param>
private void Send(string StrUrl,string bid,string showemail)
{
#region 读取配置发送邮件
string url = "http://localhost:9998/FinanceManage/CollectionManage/ConfirmCollection_Receipt.aspx?MenuID=14010600&id=" + StrUrl + "&batchID=" + bid + "";
string body = "您好,有新的待确认收款≥ "+url;
//string bcc = string.Empty;
string to = "v-zhangxy52@vanke.com";//收件人
//string cc = "";//抄送人
MailRequest mail = new MailRequest();
mail.Subject = "收款确认";//主题
mail.Body = body;//内容
// mail.Bcc = bcc;//秘密抄送人
mail.From = "v-tangqq02@vanke.com";//发送人
mail.To = to; //收件人
// mail.CC = cc; //抄送人
string sendMainResult = "-1";
if (!string.IsNullOrEmpty(mail.To.Trim()) || !string.IsNullOrEmpty(mail.CC.Trim()))
{ sendMainResult = SendMailHelper.SendMail(mail); if (string.IsNullOrEmpty(sendMainResult))
{
BaseClass.CommFun.Alert(this.up_innerCheck, "发送成功!", Page);
}
}
#endregion }
效果
点击确定发送之后,查看邮箱,即可看到发送内容(可根据业务需求自行调整)
刚好另一个项目中也需要用到发邮件,也是用的上述的帮助类,附效果图
至此,发送邮件功能已经全部完毕,当中不乏可以优化的地方,欢迎大家自行优化,相互交流~