最近在做一个项目时用到了发送邮件及接收邮件。空闲时把他总结下来、希望能帮助其他的人。
发送邮件我们使用的是SMTP协议、接收邮件使用的是POP3协议,不废话了直接上代码:
发送邮件:
namespace KylinEmailCore
{
///
/// 抽象方法
///
public abstract class PushEamilBase
{
///
/// 服务器 Smtp 服务器
///
public virtual string smtpService { get; set; }
///
/// 发送邮箱
///
public virtual string sendEmail { get; set; }
///
/// 显示名称
///
public virtual string displayName { get; set; }
///
/// 发送密码
///
public virtual string sendpwd { get; set; }
///
/// 端口
///
public virtual int sendport { get; set; }
///
/// 是否使用ssl加密
///
public virtual bool sendssl { get; set; }
//确定smtp服务器地址 实例化一个Smtp客户端
SmtpClient smtpclient = null;//实例化smtp服务器
///
/// 构造函数注入必要的参数
///
protected PushEamilBase()
{
smtpService = "smtp.xxxxx.com"; 默认的Smtp服务
sendEmail = "xxxxx";///发送邮箱
sendpwd = "xxxx";//密码
sendport = 25;
displayName = "显示名称";//Kylin displayName 就是显示的Kylin
sendssl = false;
this.smtpclient = new SmtpClient();
}
//没有采用方式
public virtual EmailSendBackDto SendEmail(EmailPushDto emailPushDto)
{
EmailSendBackDto emailSendBackDto = new EmailSendBackDto();
smtpclient.Host = smtpService;
smtpclient.Port = sendport;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(sendEmail, displayName);
//主送人
if (emailPushDto.strReceiver != null)
{
for (int i = 0; i < emailPushDto.strReceiver.Count; i++)
{
if (emailPushDto.strReceiver[i] != "")
mailMessage.To.Add(emailPushDto.strReceiver[i]);
}
}
//抄送人
if (emailPushDto.strCReceiver != null)
{
for (int i = 0; i < emailPushDto.strCReceiver.Count; i++)
{
if (emailPushDto.strCReceiver[i] != "")
mailMessage.CC.Add(emailPushDto.strCReceiver[i]);
}
}
mailMessage.Subject = emailPushDto.strSubject;//发送邮件主题
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailMessage.Body = emailPushDto.strContent;//发送邮件正文
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
//附件
if (emailPushDto.AttachFile != null)
{
foreach (string key in emailPushDto.AttachFile.Keys)
{
Attachment file = new Attachment(emailPushDto.AttachFile[key]);
file.Name = key;
mailMessage.Attachments.Add(file);
}
}
//邮件发送方式 通过网络发送到smtp服务器
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
//如果服务器支持安全连接,则将安全连接设为true
smtpclient.EnableSsl = sendssl;
try
{
//是否使用默认凭据,若为false,则使用自定义的证书,就是下面的networkCredential实例对象
smtpclient.UseDefaultCredentials = false;
//指定邮箱账号和密码,需要注意的是,这个密码是你在QQ邮箱设置里开启服务的时候给你的那个授权码
NetworkCredential networkCredential = new NetworkCredential(sendEmail, sendpwd);
smtpclient.Credentials = networkCredential;
//发送邮件
//LogManager.WriteLog("SAI发送邮件:" + mailMessage.ToJson());
smtpclient.Send(mailMessage);
emailSendBackDto.IsSuccess = true;
// to do 发送成功
}
catch (System.Net.Mail.SmtpException ex)
{
// LogManager.WriteLog("SAI发送邮箱提示错误:" + ex.Message);
emailSendBackDto.IsSuccess = false;
emailSendBackDto.Msg = ex.Message;
// to do 发送失败
}
return emailSendBackDto;
}
//采用html发送方式
public virtual EmailSendBackDto SendHtmlEmail(EmailPushDto emailPushDto)
{
EmailSendBackDto emailSendBackDto = new EmailSendBackDto();
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
//如果服务器支持安全连接,则将安全连接设为true
smtpclient.EnableSsl = sendssl;
smtpclient.Host = smtpService;//邮件服务器
smtpclient.UseDefaultCredentials = true;
smtpclient.Credentials = new NetworkCredential(sendEmail, sendpwd);//用户名、密码
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(sendEmail, displayName);
if (emailPushDto.strReceiver != null)
{
for (int i = 0; i < emailPushDto.strReceiver.Count; i++)
{
mailMessage.To.Add(emailPushDto.strReceiver[i]);
}
}
if (emailPushDto.strCReceiver != null)
{
for (int i = 0; i < emailPushDto.strCReceiver.Count; i++)
{
mailMessage.CC.Add(emailPushDto.strCReceiver[i]);
}
}
mailMessage.Subject = emailPushDto.strSubject;//邮件标题
mailMessage.Body = emailPushDto.strContent;//发送邮件正文
//mailMessage.Body = emailPushDto.strContent;//邮件内容
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
mailMessage.IsBodyHtml = true;//是否是HTML邮件
mailMessage.Priority = MailPriority.High;//邮件优先级
//附件
if (emailPushDto.AttachFile != null)
{
foreach (string key in emailPushDto.AttachFile.Keys)
{
Attachment file = new Attachment(emailPushDto.AttachFile[key]);
file.Name = key;
mailMessage.Attachments.Add(file);
}
}
try
{
smtpclient.Send(mailMessage);
emailSendBackDto.IsSuccess = true;
}
catch (System.Net.Mail.SmtpException ex)
{
emailSendBackDto.IsSuccess = true;
emailSendBackDto.Msg = ex.Message;
}
return emailSendBackDto;
}
}
}
接收邮件:
namespace KylinEmailCore
{
///
/// 接收邮件
///
public class ReveiveEamilBase
{
///
/// 存在本地地址
///
public virtual string localfile { get; set; }
///
/// 服务器 Smtp 服务器
///
public virtual string smtpService { get; set; }
///
/// 发送邮箱
///
public virtual string sendEmail { get; set; }
///
/// 发送密码
///
public virtual string sendpwd { get; set; }
///
/// 端口
///
public virtual int sendport { get; set; }
///
/// 是否使用ssl加密
///
public virtual bool sendssl { get; set; }
//实例化对象
Pop3Client pop3;
public ReveiveEamilBase()
{
smtpService = "pop.qiye.aliyun.com"; //"smtp.mxhichina.com.cn";//默认的Smtp服务
sendEmail = "sgdsrm@cetccq.com.cn";// "cetccq_ic@vip.163.com";//发送邮箱
sendpwd = "Sgd_Srm_12";//密码
sendport = 110;//端口
sendssl = false;
localfile = "D:\\localfile";
pop3 = new Pop3Client();
}
///
/// 接受邮件 Openpop
/// 邮件接收:.NET中没有POP3邮件接收的类,邮件的内容和格式比复杂,
/// 手动写代码进行解析很麻烦,也容易出错,开发中我们可以借助第三方插件来实现
/// OpenPOP.NET插件的地址:http://sourceforge.net/projects/hpop/
///
///
public virtual List ReceiveEmail()
{
List reveiveEamilBackDtos = new List();
try
{
//链接到邮件服务器
pop3.Connect(smtpService, sendport, sendssl);
//身份验证
pop3.Authenticate(sendEmail, sendpwd);
//读邮件列表
//1.获取邮件的个数
int count = pop3.GetMessageCount();
//2.遍历显示出来
for (int i = 1; i <= count; i++)
{
Message msg = pop3.GetMessage(i);
string FromAddress = msg.Headers.From.Address;//发送者的邮箱地址
string FromDisplayName = msg.Headers.From.DisplayName;//发送者的名子
DateTime DateSent = msg.Headers.DateSent;//邮件的发送时间
string Subject = msg.Headers.Subject;//邮件的主题
//获取正文内容,其中包括\n\r这些换行符
string Body = String.Empty;
try
{
Body = msg.FindFirstPlainTextVersion().GetBodyAsText();
}
catch (Exception ex)
{
}
//获取邮件html内容
//OpenPop.Mime.MessagePart htmlMessage = msg.FindFirstHtmlVersion();
//string htmlText = htmlMessage.GetBodyAsText();
//只要有附件才添加到集合
List messageParts = msg.FindAllAttachments();
if (messageParts != null)
{
if (messageParts.Count > 0)
{
ReveiveEamilBackDto reveiveEamilBackDto = new ReveiveEamilBackDto();
reveiveEamilBackDto.FromAddress = FromAddress;//发送者的邮箱
reveiveEamilBackDto.FromDisplayName = FromDisplayName;//发送者的名称
reveiveEamilBackDto.BodyAsText = Body;//文本
reveiveEamilBackDto.Subject = Subject;//title
reveiveEamilBackDto.DateSent = DateSent;//发送日期
//附件
reveiveEamilBackDto.fileLists = new List();
foreach (MessagePart item in messageParts)
{
FileList fileList = new FileList();
//判断文件是否存在,不存在则创建的存在
string sPath = Path.Combine(localfile, "File");
if (!System.IO.Directory.Exists(sPath))
{
//创建该文件
System.IO.Directory.CreateDirectory(sPath);
}
FileInfo fileInfo = new FileInfo(sPath + "\\" + item.FileName);
//保存附件
item.Save(fileInfo);
//添加附件
fileList.DownDate = DateTime.Now;
fileList.FileName = item.FileName;
fileList.FilePath = fileInfo.FullName;
reveiveEamilBackDto.fileLists.Add(fileList);
}
reveiveEamilBackDtos.Add(reveiveEamilBackDto);
}
}
//暂时不需要删除 在测试阶段
pop3.DeleteMessage(i); //删除邮件
}
//断开链接
pop3.Disconnect();
}
catch (Exception ex)
{
}
return reveiveEamilBackDtos;
}
}
}
源码:
https://github.com/lszai90/SendAndReceiveEmail.git
日行一结,既能利于别人,也能利于己。## 导言
最近在做一个项目时用到了发送邮件及接收邮件。空闲时把他总结下来、希望能帮助其他的人。
发送邮件我们使用的是SMTP协议、接收邮件使用的是POP3协议,不废话了直接上代码:
发送邮件:
namespace KylinEmailCore
{
///
/// 抽象方法
///
public abstract class PushEamilBase
{
///
/// 服务器 Smtp 服务器
///
public virtual string smtpService { get; set; }
///
/// 发送邮箱
///
public virtual string sendEmail { get; set; }
///
/// 显示名称
///
public virtual string displayName { get; set; }
///
/// 发送密码
///
public virtual string sendpwd { get; set; }
///
/// 端口
///
public virtual int sendport { get; set; }
///
/// 是否使用ssl加密
///
public virtual bool sendssl { get; set; }
//确定smtp服务器地址 实例化一个Smtp客户端
SmtpClient smtpclient = null;//实例化smtp服务器
///
/// 构造函数注入必要的参数
///
protected PushEamilBase()
{
smtpService = "smtp.xxxxx.com"; 默认的Smtp服务
sendEmail = "xxxxx";///发送邮箱
sendpwd = "xxxx";//密码
sendport = 25;
displayName = "显示名称";//Kylin displayName 就是显示的Kylin
sendssl = false;
this.smtpclient = new SmtpClient();
}
//没有采用方式
public virtual EmailSendBackDto SendEmail(EmailPushDto emailPushDto)
{
EmailSendBackDto emailSendBackDto = new EmailSendBackDto();
smtpclient.Host = smtpService;
smtpclient.Port = sendport;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(sendEmail, displayName);
//主送人
if (emailPushDto.strReceiver != null)
{
for (int i = 0; i < emailPushDto.strReceiver.Count; i++)
{
if (emailPushDto.strReceiver[i] != "")
mailMessage.To.Add(emailPushDto.strReceiver[i]);
}
}
//抄送人
if (emailPushDto.strCReceiver != null)
{
for (int i = 0; i < emailPushDto.strCReceiver.Count; i++)
{
if (emailPushDto.strCReceiver[i] != "")
mailMessage.CC.Add(emailPushDto.strCReceiver[i]);
}
}
mailMessage.Subject = emailPushDto.strSubject;//发送邮件主题
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailMessage.Body = emailPushDto.strContent;//发送邮件正文
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
//附件
if (emailPushDto.AttachFile != null)
{
foreach (string key in emailPushDto.AttachFile.Keys)
{
Attachment file = new Attachment(emailPushDto.AttachFile[key]);
file.Name = key;
mailMessage.Attachments.Add(file);
}
}
//邮件发送方式 通过网络发送到smtp服务器
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
//如果服务器支持安全连接,则将安全连接设为true
smtpclient.EnableSsl = sendssl;
try
{
//是否使用默认凭据,若为false,则使用自定义的证书,就是下面的networkCredential实例对象
smtpclient.UseDefaultCredentials = false;
//指定邮箱账号和密码,需要注意的是,这个密码是你在QQ邮箱设置里开启服务的时候给你的那个授权码
NetworkCredential networkCredential = new NetworkCredential(sendEmail, sendpwd);
smtpclient.Credentials = networkCredential;
//发送邮件
//LogManager.WriteLog("SAI发送邮件:" + mailMessage.ToJson());
smtpclient.Send(mailMessage);
emailSendBackDto.IsSuccess = true;
// to do 发送成功
}
catch (System.Net.Mail.SmtpException ex)
{
// LogManager.WriteLog("SAI发送邮箱提示错误:" + ex.Message);
emailSendBackDto.IsSuccess = false;
emailSendBackDto.Msg = ex.Message;
// to do 发送失败
}
return emailSendBackDto;
}
//采用html发送方式
public virtual EmailSendBackDto SendHtmlEmail(EmailPushDto emailPushDto)
{
EmailSendBackDto emailSendBackDto = new EmailSendBackDto();
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
//如果服务器支持安全连接,则将安全连接设为true
smtpclient.EnableSsl = sendssl;
smtpclient.Host = smtpService;//邮件服务器
smtpclient.UseDefaultCredentials = true;
smtpclient.Credentials = new NetworkCredential(sendEmail, sendpwd);//用户名、密码
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(sendEmail, displayName);
if (emailPushDto.strReceiver != null)
{
for (int i = 0; i < emailPushDto.strReceiver.Count; i++)
{
mailMessage.To.Add(emailPushDto.strReceiver[i]);
}
}
if (emailPushDto.strCReceiver != null)
{
for (int i = 0; i < emailPushDto.strCReceiver.Count; i++)
{
mailMessage.CC.Add(emailPushDto.strCReceiver[i]);
}
}
mailMessage.Subject = emailPushDto.strSubject;//邮件标题
mailMessage.Body = emailPushDto.strContent;//发送邮件正文
//mailMessage.Body = emailPushDto.strContent;//邮件内容
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
mailMessage.IsBodyHtml = true;//是否是HTML邮件
mailMessage.Priority = MailPriority.High;//邮件优先级
//附件
if (emailPushDto.AttachFile != null)
{
foreach (string key in emailPushDto.AttachFile.Keys)
{
Attachment file = new Attachment(emailPushDto.AttachFile[key]);
file.Name = key;
mailMessage.Attachments.Add(file);
}
}
try
{
smtpclient.Send(mailMessage);
emailSendBackDto.IsSuccess = true;
}
catch (System.Net.Mail.SmtpException ex)
{
emailSendBackDto.IsSuccess = true;
emailSendBackDto.Msg = ex.Message;
}
return emailSendBackDto;
}
}
}
接收邮件:
namespace KylinEmailCore
{
///
/// 接收邮件
///
public class ReveiveEamilBase
{
///
/// 存在本地地址
///
public virtual string localfile { get; set; }
///
/// 服务器 Smtp 服务器
///
public virtual string smtpService { get; set; }
///
/// 发送邮箱
///
public virtual string sendEmail { get; set; }
///
/// 发送密码
///
public virtual string sendpwd { get; set; }
///
/// 端口
///
public virtual int sendport { get; set; }
///
/// 是否使用ssl加密
///
public virtual bool sendssl { get; set; }
//实例化对象
Pop3Client pop3;
public ReveiveEamilBase()
{
smtpService = "pop.qiye.aliyun.com"; //"smtp.mxhichina.com.cn";//默认的Smtp服务
sendEmail = "sgdsrm@cetccq.com.cn";// "cetccq_ic@vip.163.com";//发送邮箱
sendpwd = "Sgd_Srm_12";//密码
sendport = 110;//端口
sendssl = false;
localfile = "D:\\localfile";
pop3 = new Pop3Client();
}
///
/// 接受邮件 Openpop
/// 邮件接收:.NET中没有POP3邮件接收的类,邮件的内容和格式比复杂,
/// 手动写代码进行解析很麻烦,也容易出错,开发中我们可以借助第三方插件来实现
/// OpenPOP.NET插件的地址:http://sourceforge.net/projects/hpop/
///
///
public virtual List ReceiveEmail()
{
List reveiveEamilBackDtos = new List();
try
{
//链接到邮件服务器
pop3.Connect(smtpService, sendport, sendssl);
//身份验证
pop3.Authenticate(sendEmail, sendpwd);
//读邮件列表
//1.获取邮件的个数
int count = pop3.GetMessageCount();
//2.遍历显示出来
for (int i = 1; i <= count; i++)
{
Message msg = pop3.GetMessage(i);
string FromAddress = msg.Headers.From.Address;//发送者的邮箱地址
string FromDisplayName = msg.Headers.From.DisplayName;//发送者的名子
DateTime DateSent = msg.Headers.DateSent;//邮件的发送时间
string Subject = msg.Headers.Subject;//邮件的主题
//获取正文内容,其中包括\n\r这些换行符
string Body = String.Empty;
try
{
Body = msg.FindFirstPlainTextVersion().GetBodyAsText();
}
catch (Exception ex)
{
}
//获取邮件html内容
//OpenPop.Mime.MessagePart htmlMessage = msg.FindFirstHtmlVersion();
//string htmlText = htmlMessage.GetBodyAsText();
//只要有附件才添加到集合
List messageParts = msg.FindAllAttachments();
if (messageParts != null)
{
if (messageParts.Count > 0)
{
ReveiveEamilBackDto reveiveEamilBackDto = new ReveiveEamilBackDto();
reveiveEamilBackDto.FromAddress = FromAddress;//发送者的邮箱
reveiveEamilBackDto.FromDisplayName = FromDisplayName;//发送者的名称
reveiveEamilBackDto.BodyAsText = Body;//文本
reveiveEamilBackDto.Subject = Subject;//title
reveiveEamilBackDto.DateSent = DateSent;//发送日期
//附件
reveiveEamilBackDto.fileLists = new List();
foreach (MessagePart item in messageParts)
{
FileList fileList = new FileList();
//判断文件是否存在,不存在则创建的存在
string sPath = Path.Combine(localfile, "File");
if (!System.IO.Directory.Exists(sPath))
{
//创建该文件
System.IO.Directory.CreateDirectory(sPath);
}
FileInfo fileInfo = new FileInfo(sPath + "\\" + item.FileName);
//保存附件
item.Save(fileInfo);
//添加附件
fileList.DownDate = DateTime.Now;
fileList.FileName = item.FileName;
fileList.FilePath = fileInfo.FullName;
reveiveEamilBackDto.fileLists.Add(fileList);
}
reveiveEamilBackDtos.Add(reveiveEamilBackDto);
}
}
//暂时不需要删除 在测试阶段
pop3.DeleteMessage(i); //删除邮件
}
//断开链接
pop3.Disconnect();
}
catch (Exception ex)
{
}
return reveiveEamilBackDtos;
}
}
}
源码:
https://github.com/lszai90/SendAndReceiveEmail.git
博客地址:
https://lszai90.github.io/
日行一结,既能利于别人,也能利于己。