C#发送邮件代码
- using System;
- using System.Net;
- using System.Net.Mail;
- using System.Net.Mime;
- namespace Fish
- {
- /**/
- ///
- /// 发送邮件的类
- ///
- public class SendMail
- {
- private MailMessage mailMessage = new MailMessage();
- private SmtpClient smtpClient;
- private string password;//发件人密码
- /**/
- ///
- /// 设置收件人、发件人信息与邮件内容、标题
- ///
- /// 收件人地址
- /// 发件人地址
- /// 邮件正文
- /// 邮件的主题
- /// 发件人密码
- public void Mail(string To, string From, string Body, string Title, string Password)
- {
- mailMessage.To.Add(To);
- mailMessage.From = new System.Net.Mail.MailAddress(From);
- mailMessage.Subject = Title;
- mailMessage.Body = Body;
- mailMessage.IsBodyHtml = true;
- mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
- mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
- this.password = Password;
- }
- /**/
- ///
- /// 添加附件
- ///
- public void Attachments(string Path)
- {
- string[] path = Path.Split(',');
- Attachment data;
- ContentDisposition disposition;
- for (int i = 0; i < path.Length; i++)
- {
- data = new Attachment(path[i], MediaTypeNames.Application.Octet);//实例化 附件
- disposition = data.ContentDisposition;
- disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);//获取 附件的创建日期
- disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);// 获取附件的修改日期
- disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);//获取附 件的读取日期
- mailMessage.Attachments.Add(data);//添加到附件中
- }
- }
- /**/
- ///
- /// 异步发送邮件
- ///
- ///
- public void SendAsync(SendCompletedEventHandler CompletedMethod)
- {
- if (mailMessage != null)
- {
- smtpClient = new SmtpClient();
- smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据
- smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
- smtpClient.Host = "smtp." + mailMessage.From.Host;
- smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);//注册异步发送邮件完成时的事件
- smtpClient.SendAsync(mailMessage, mailMessage.Body);
- }
- }
- /**/
- ///
- /// 发送邮件
- ///
- public void Send()
- {
- if (mailMessage != null)
- {
- smtpClient = new SmtpClient();
- smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据
- smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
- smtpClient.Host = "smtp." + mailMessage.From.Host;
- smtpClient.Send(mailMessage);
- }
- }
- ///
- /// 根据索引删除附件
- ///
- ///
- public void DeleteAttachments(int Id)
- {
- mailMessage.Attachments.RemoveAt(Id);
- }
- }
- }
创新互联建站是专业的大悟网站建设公司,大悟接单;提供网站设计、成都做网站,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行大悟网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
文章标题:C#发送邮件代码
文章分享:http://myzitong.com/article/gijjhi.html