C#代码发送邮件
本次测试的邮箱为163邮箱
1、首相对邮箱进行一些设置(详见下图);打开设置选取客户端授权密码项,开启设置;以后在客户端登录时将使用刚刚设置的密码!
2、上干货
1 public static void TestEmail2() 2 { 3 try 4 { 5 //确定smtp服务器地址。实例化一个Smtp客户端 6 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.163.com "); 7 //生成一个发送地址 8 string strFrom = string.Empty; 9 strFrom = "发送的邮箱@163.com"; 10 //构造一个发件人地址对象 11 MailAddress from = new MailAddress(strFrom, "发件人", Encoding.UTF8); 12 //构造一个收件人地址对象 例如123456@qq.com 13 MailAddress to = new MailAddress("收件邮箱", "收件人", Encoding.UTF8); 14 //构造一个Email的Message对象 15 MailMessage message = new MailMessage(from, to); 16 //得到文件名 17 string fileName = @"附件文件地址"; 18 //判断文件是否存在 19 if (File.Exists(fileName)) 20 { 21 //构造一个附件对象 22 Attachment attach = new Attachment(fileName); 23 //得到文件的信息 24 ContentDisposition disposition = attach.ContentDisposition; 25 disposition.CreationDate = System.IO.File.GetCreationTime(fileName); 26 disposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName); 27 disposition.ReadDate = System.IO.File.GetLastAccessTime(fileName); 28 //向邮件添加附件 29 message.Attachments.Add(attach); 30 } 31 else 32 { 33 Log4Net.LogHelper.WriteLog(typeof(EmailService), "文件" + fileName + "未找到!"); 34 } 35 //添加邮件主题和内容 36 message.Subject = "主题"; 37 message.SubjectEncoding = Encoding.UTF8; 38 message.Body = "邮件内容"; 39 message.BodyEncoding = Encoding.UTF8; 40 //设置邮件的信息 41 client.DeliveryMethod = SmtpDeliveryMethod.Network; 42 message.BodyEncoding = System.Text.Encoding.UTF8; 43 message.IsBodyHtml = false; 44 45 //gmail支持,163不支持,如果是gmail则一定要将其设为true 46 client.EnableSsl = false; 47 48 //设置用户名和密码。 49 client.UseDefaultCredentials = false; 50 string username = "邮箱名(无163后缀)"; 51 string passwd = "刚刚设置的客户端授权码"; 52 //用户登陆信息 53 NetworkCredential myCredentials = new NetworkCredential(username, passwd); 54 client.Credentials = myCredentials; 55 //发送邮件 56 client.Send(message); 57 //提示发送成功 58 } 59 catch (Exception ex) 60 { 61 Log4Net.LogHelper.WriteLog(typeof(EmailService), ex.Message); 62 } 63 }