net中c#想实现邮件的操作,推荐使用Aspose.Network组件。需要注意的是,这个组件名字现在改成Aspose.Email了,但我们这里用的还是旧版本(博客结尾提供DLL文件下载)
这里有个点要注意下,用代码实现邮件操作时,使用的是密码不是登录密码,而是要生成第三方的授权码。这里以QQ邮箱为例,一般就在IMAP、SMTP服务下面,点击“新增授权码”,点击后会要求使用注册邮箱的手机号码发送一条验证短信至邮箱要求的号码,具体短信内容根据不同的邮箱要求不一样,根据实际要求发送短信,发送后点击“我已发送”,就会出现当前生成的邮箱授权码即可。
发送邮件的完整代码,PS:直接Copy即可
public static class MessageUtil { public static List<EMailOptionModel> EMailOptions { get; set; } public static Dictionary<string,string> SMSErors { get; set; } /// <summary> /// 构造函数 /// </summary> static MessageUtil() { //EMail邮箱服务器配置 MessageUtil.EMailOptions = new List<EMailOptionModel>(); MessageUtil.EMailOptions.Add(new EMailOptionModel() { ServerType = EMailServerType.NetEase163POP, ServerName = "pop.163.com", Port = 110 }); MessageUtil.EMailOptions.Add(new EMailOptionModel() { ServerType = EMailServerType.QQPOP, ServerName = "pop.qq.com", Port = 110, PortInSSL = 995 }); MessageUtil.EMailOptions.Add(new EMailOptionModel() { ServerType = EMailServerType.NetEase163SMTP, ServerName = "smtp.163.com", Port = 25 }); MessageUtil.EMailOptions.Add(new EMailOptionModel() { ServerType = EMailServerType.QQSMTP, ServerName = "smtp.qq.com", Port = 25, PortInSSL = 465 }); //获取短信发送错误码 MessageUtil.SMSErors = new Dictionary<string, string>(); MessageUtil.SMSErors.Add("-1", "用户名或者密码不正确或用户禁用或者是管理账户"); MessageUtil.SMSErors.Add("0", "发送短信失败"); MessageUtil.SMSErors.Add("2", "余额不够或扣费错误"); MessageUtil.SMSErors.Add("3", "扣费失败异常(请联系客服)"); MessageUtil.SMSErors.Add("6", "有效号码为空"); MessageUtil.SMSErors.Add("7", "短信内容为空"); MessageUtil.SMSErors.Add("8", "无签名,必须,格式:[签名]"); MessageUtil.SMSErors.Add("9", "没有Url提交权限"); MessageUtil.SMSErors.Add("10", "发送号码过多,最多支持2000个号码"); MessageUtil.SMSErors.Add("11", "产品ID异常或产品禁用"); MessageUtil.SMSErors.Add("12", "参数异常"); MessageUtil.SMSErors.Add("13", "tkey参数错误"); MessageUtil.SMSErors.Add("15", "Ip验证失败"); MessageUtil.SMSErors.Add("16", "xh参数错误"); MessageUtil.SMSErors.Add("19", "短信内容过长,最多支持500个,或提交编码异常导致"); } /// <summary> /// 获取邮箱服务器配置信息 /// </summary> /// <param name="serverType"></param> /// <returns></returns> public static EMailOptionModel SingleEMailOption(EMailServerType serverType) { EMailOptionModel pModel = MessageUtil.EMailOptions.FirstOrDefault(c => c.ServerType == serverType); return pModel; } /// <summary> /// 检测邮件附件大小,规定是10M以内 /// </summary> /// <param name="fileFullName"></param> /// <param name="message"></param> /// <returns></returns> public static bool CheckEMailAttachSize(string fileFullName, ref string message) { try { FileStream FileStream_my = new FileStream(fileFullName, FileMode.Open); string name = FileStream_my.Name; int size = (int)(FileStream_my.Length / 1024 / 1024); FileStream_my.Close(); //控制文件大小不大于10M if (size > 10) { message = "文件长度不能大于10M!你选择的文件大小为" + size.ToString() + "M"; return false; } return true; } catch (IOException ex) { message = ex.Message; return false; } } /// <summary> /// 获取指定邮箱邮件个数 /// </summary> /// <param name="serverType"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static int GetEMailCount(EMailServerType serverType, string userName, string password) { int emailCount = 0; //获取邮箱配置信息.若不存在,则直接返回0 EMailOptionModel emailOption = MessageUtil.SingleEMailOption(serverType); if (emailOption == null) return emailCount; //建立连接.格式:Pop3Client(邮件POP,端口,用户名,密码) Aspose.Network.Pop3.Pop3Client emailClient = new Aspose.Network.Pop3.Pop3Client(emailOption.ServerName, emailOption.Port, userName, password); //连接并且登录 emailClient.Connect(true); //获取邮件个数 emailCount = emailClient.GetMessageCount(); return emailCount; } /// <summary> /// 获取指定邮箱邮件列表 /// </summary> /// <param name="serverType"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="attachPath">附件存放文件夹</param> /// <param name="getEmailCount">获取邮件个数</param> /// <returns></returns> public static List<EMailContentModel> GetListEMail(EMailServerType serverType, string userName, string password, string attachPath, int? getEmailCount) { List<EMailContentModel> listEMail = new List<EMailContentModel>(); //获取邮箱配置信息.若不存在,则直接返回0 EMailOptionModel emailOption = MessageUtil.SingleEMailOption(serverType); if (emailOption == null) return listEMail; //建立连接.格式:Pop3Client(邮件POP,端口,用户名,密码) Aspose.Network.Pop3.Pop3Client emailClient = new Aspose.Network.Pop3.Pop3Client(emailOption.ServerName, emailOption.Port, userName, password); //连接并且登录 emailClient.Connect(true); //获取邮件个数,并开始获取 int emailCount = emailClient.GetMessageCount(); if (getEmailCount.HasValue) { //若有值,则取两者最小值 emailCount = Math.Min(emailCount, getEmailCount.Value); } for (int i = 1; i <= emailCount; i++) { //单条邮件实体 EMailContentModel ModelMail = new EMailContentModel(); //获取单条邮件 Aspose.Network.Mail.MailMessage MailMsg = emailClient.FetchMessage(i); string MessageID = emailClient.GetMessageUniqueId(i); //邮件唯一ID ModelMail.Date = MailMsg.Date; //发送时间 ModelMail.Subject = MailMsg.Subject; //主题 ModelMail.Body = MailMsg.HtmlBody; //内容 for (int j = 0; j < MailMsg.To.Count; j++) //收件人 { ModelMail.Tos += MailMsg.To[j].Address + ";"; ModelMail.TosName += MailMsg.To[j].DisplayName + "<" + MailMsg.To[j].Address + ">"; } for (int j = 0; j < MailMsg.CC.Count; j++) //抄送 { ModelMail.CC += MailMsg.CC[j].Address + ";"; ModelMail.CCName += MailMsg.CC[j].DisplayName + "<" + MailMsg.CC[j].Address + ">"; } for (int j = 0; j < MailMsg.From.Count; j++) //发送人 { ModelMail.From += MailMsg.From[j].Address + ";"; ModelMail.FromName += MailMsg.From[j].DisplayName + "<" + MailMsg.From[j].Address + ">"; } string path = string.Empty; Aspose.Network.Mail.AttachmentCollection atts = MailMsg.Attachments; //获取附件 foreach (var att in atts) { path = attachPath + @"\" + MessageID + @"\"; if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } att.Save(path + att.Name); ModelMail.Att += att.Name + ";"; } Aspose.Network.Mail.LinkedResourceCollection MailLink = MailMsg.LinkedResources; //内嵌附件 foreach (var list in MailLink) { if (string.IsNullOrEmpty(list.Name)) continue; string ContentId = list.ContentId; path = attachPath + @"\" + MessageID + @"\"; if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } list.Save(path + list.Name); ModelMail.Body = ModelMail.Body.Replace("cid:" + ContentId, "/Att/" + MessageID + "/" + list.Name);//替换内容中的内嵌附件 } listEMail.Add(ModelMail); //删除服务器上的原始邮件 //Pop3.DeleteMessage(i); } //断开链接 emailClient.Disconnect(); return listEMail; } /// <summary> /// 发送邮件,根据指定邮箱 /// </summary> /// <param name="serverType"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="emailModel"></param> public static void SendEMail(EMailServerType serverType, string userName, string password, EMailContentModel emailContent) { string message = null; //根据服务器类型,获取配置信息 EMailOptionModel emailOption = MessageUtil.SingleEMailOption(serverType); if (emailOption == null) { message = "获取邮箱服务器配置失败"; throw new Exception(message); } //参数检测 string stmpServerName = emailOption.ServerName; int port = emailOption.Port; if (string.IsNullOrEmpty(stmpServerName) ) { message = "请输入SMTP服务器名"; throw new Exception(message); } if (string.IsNullOrEmpty(userName) ) { message = "请输入发件人邮箱地址"; throw new Exception(message); } if (string.IsNullOrEmpty(password) ) { message = "请输入发件人邮箱密码"; throw new Exception(message); } if (string.IsNullOrEmpty(emailContent.Tos)) { message = "获取收件人地址失败"; throw new Exception(message); } System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = false; smtpClient.Host = stmpServerName; //指定SMTP服务名.例如QQ邮箱为smtp.qq.com;新浪cn邮箱为smtp.sina.cn等 smtpClient.Port = port; //指定端口号 smtpClient.Timeout = 15 * 1000; //超时时间(15s) //指定发件人信息,包括邮箱地址和邮箱密码 smtpClient.Credentials = new System.Net.NetworkCredential(userName, password); //设置发送路径 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //清空历史发送信息,以防发送时收件人收到的错误信息(收件人列表会不断重复) System.Net.Mail.MailMessage mailMessageMain = new System.Net.Mail.MailMessage(); mailMessageMain.To.Clear(); //添加收件人邮箱地址 string[] arrayTo = emailContent.Tos.Split(','); foreach (string to in arrayTo) { System.Net.Mail.MailAddress mailAddress_to = new System.Net.Mail.MailAddress(to); mailMessageMain.To.Add(mailAddress_to); } //发件人邮箱 mailMessageMain.From = new System.Net.Mail.MailAddress(userName, userName); //邮件主题 mailMessageMain.Subject = emailContent.Subject; mailMessageMain.SubjectEncoding = System.Text.Encoding.UTF8; //邮件正文 mailMessageMain.Body = emailContent.Body; mailMessageMain.BodyEncoding = System.Text.Encoding.UTF8; //清空历史附件 以防附件重复发送 mailMessageMain.Attachments.Clear(); //添加附件.检测附件大小,必需小于10M;否则返回 if (!string.IsNullOrEmpty(emailContent.Att)) { string[] attachFiles = emailContent.Att.Split(','); if (attachFiles.Length > 0) { foreach (string attachFile in attachFiles) { bool checkResult = MessageUtil.CheckEMailAttachSize(attachFile, ref message); if (checkResult == true) { mailMessageMain.Attachments.Add(new System.Net.Mail.Attachment(attachFile, System.Net.Mime.MediaTypeNames.Application.Octet)); } else { throw new Exception("检测附件失败"); } } } } //开始发送邮件 smtpClient.Send(mailMessageMain); } }
使用到的枚举和Model类
/// <summary> /// 邮箱服务器类型 /// </summary> public enum EMailServerType { /// <summary> /// 网易163,POP服务器 /// </summary> [DisplayText("网易", "NetEase163POP")] NetEase163POP, /// <summary> /// 网易163,SMTP服务器 /// </summary> [DisplayText("网易", "NetEase163SMTP")] NetEase163SMTP, /// <summary> /// 腾讯QQ,POP服务器 /// </summary> [DisplayText("腾讯", "QQPOP")] QQPOP, /// <summary> /// 腾讯QQ,SMTP服务器 /// </summary> [DisplayText("腾讯", "QQSMTP")] QQSMTP } /// <summary> /// EMail发送邮件实体类 /// </summary> public class EMailContentModel { /// <summary> /// 流水号 /// </summary> public int ListID { get; set; } /// <summary> /// 主题 /// </summary> public string Subject { get; set; } /// <summary> /// 内容 /// </summary> public string Body { get; set; } /// <summary> /// 收件人列表,逗号分隔 /// </summary> public string Tos { get; set; } /// <summary> /// 收件人名称列表,逗号分隔 /// </summary> public string TosName { get; set; } /// <summary> /// 抄送 /// </summary> public string CC { get; set; } /// <summary> /// 抄送人姓名 /// </summary> public string CCName { get; set; } /// <summary> /// 发送人 /// </summary> public string From { get; set; } /// <summary> /// 发送人姓名 /// </summary> public string FromName { get; set; } /// <summary> /// 附件 /// </summary> public string Att { get; set; } /// <summary> /// 时间 /// </summary> public DateTime Date { get; set; } /// <summary> /// 使用SSL协议 /// </summary> public bool InSSL { get; set; } } /// <summary> /// EMail邮箱配置实体类 /// </summary> public class EMailOptionModel { public EMailServerType ServerType { get; set; } public string ServerName { get; set; } public int Port { get; set; } public int PortInSSL { get; set; } public string UserName { get; set; } public string Password { get; set; } }
调用示例
string userName = "15878@qq.com"; string password = "oitnjhwcbac"; int emailCount = MessageUtil.GetEMailCount(EMailServerType.QQPOP, userName, password);
文章评论