上一篇试用了c#的WebClient下载文件功能,这次再来看看Mail类发送邮件的功能,参考网上的教程,分别测试了163和QQ邮箱的smtp功能,其中QQ邮箱比较难以配置,试了几次最终还是成功了,主要两点:启用SSL,设置端口(smtp.qq.com special sets下面的额外配置),添加了超时时间是为了在添加附件的时候能多等待一会儿。其余的基本上都是通用的,测试代码如下,比较简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Mail; namespace mailSend { class mailSend { static void Main(string[] args) { string fPath; string fName = "DSC_0625.NEF"; string receiver="523456721@qq.com"; SmtpClient mySmtpClient = new SmtpClient(); MailMessage myEmail = new MailMessage(); mySmtpClient.Host = "smtp.qq.com"; mySmtpClient.UseDefaultCredentials = true; mySmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; mySmtpClient.Credentials = new System.Net.NetworkCredential("88110620", "adanpldatmfsbfhe"); // //smtp.qq.com special sets mySmtpClient.EnableSsl = true; mySmtpClient.Port = 587; mySmtpClient.Timeout = 1000*60*3; myEmail.From = new MailAddress("88110620@qq.com"); myEmail.To.Add(receiver); myEmail.Subject = fName; myEmail.Body = fName; myEmail.SubjectEncoding = Encoding.UTF8; myEmail.BodyEncoding = Encoding.UTF8; myEmail.Priority = MailPriority.High; myEmail.IsBodyHtml = true; try { fPath = System.Environment.CurrentDirectory; Attachment attachFile = new Attachment(fPath +"/"+ fName); myEmail.Attachments.Add(attachFile); } catch (Exception ex) { Console.WriteLine(ex.Message); } mySmtpClient.Send(myEmail); // Console.ReadKey(); } } } |
非常令人遗憾的是QQ的大附件(文件中转站)没法子直接使用,让期望与现实的落差变得巨大巨大,因为用QQ邮箱主要就是为了发大附件,要是这一块没办法实现,也就没有多少意义了。