項目中遇到一個郵件發送功能,使用常用的的SmtpClient進行發送,在本地進行了126的郵箱進行測試通過,客戶發來對應的郵箱資訊後告知是使用的是465加密端口,SSL加密協定,再把相關資訊進行配置替換後發現郵件發送一直報逾時,一直也找不到原因。網上進行相關資料查詢最終查閱到:“”465端口是Implicit SSL,由于.net FrameWork 的Bug,不能使用SmtpClint發送Implicit SSL郵件:(未去真實核對),最終在網上找到相關資料使用CDO的COM元件。
方法如下:
1、添加引用 -> COM -> Microsoft CDO for Windows2000 Library
2、在代碼中引入命名空間: using CDO;
3、詳細代碼:
1. /// <summary>
2. /// 針對465加密端口 加密協定SSL(Implicit SSL)進行的郵件發送
3. /// </summary>
4. public void SendMailForSSL()
5. {
6. try
7. {
8. CDO.Message oMsg = new CDO.Message();
9. Configuration conf = new ConfigurationClass();
10. conf.Fields[CdoConfiguration.cdoSendUsingMethod].Value = CdoSendUsing.cdoSendUsingPort;
11. conf.Fields[CdoConfiguration.cdoSMTPAuthenticate].Value = CdoProtocolsAuthentication.cdoBasic;
12. conf.Fields[CdoConfiguration.cdoSMTPUseSSL].Value = true;
13. conf.Fields[CdoConfiguration.cdoSMTPServer].Value = this.Host;//必填,而且要真實可用
14. conf.Fields[CdoConfiguration.cdoSMTPServerPort].Value = this.Port;//465特有
15. conf.Fields[CdoConfiguration.cdoSendEmailAddress].Value = "<" + this.From + ">";
16. conf.Fields[CdoConfiguration.cdoSendUserName].Value = this.From;//真實的郵件位址
17. conf.Fields[CdoConfiguration.cdoSendPassword].Value = this.Password; //為郵箱密碼,必須真實
18.
19.
20. conf.Fields.Update();
21.
22. oMsg.Configuration = conf;
23. oMsg.HTMLBody = this.Body;
24.
25. oMsg.Subject = this.Subject;
26.
27. oMsg.From = this.From;
28. oMsg.To = this.To;
29. //ADD attachment.
30. //TODO: Change the path to the file that you want to attach.
31. //oMsg.AddAttachment("C:\Hello.txt", "", "");
32. //oMsg.AddAttachment("C:\Test.doc", "", "");
33. oMsg.Send();
34. }
35. catch (System.Net.Mail.SmtpException ex)
36. {
37. throw ex;
38. }
39. }
另:
1、提示:在VS2010,在引用COM元件的時候,出現了無法嵌入互操作類型“……”,請改用适用的接口的錯誤提示。