SmtpClient.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. //
  2. // System.Web.Mail.SmtpClient.cs
  3. //
  4. // Author(s):
  5. // Per Arneng <[email protected]>
  6. // Sanjay Gupta <[email protected]>
  7. // (C) 2004, Novell, Inc. (http://www.novell.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Net;
  30. using System.IO;
  31. using System.Text;
  32. using System.Collections;
  33. using System.Net.Sockets;
  34. using System.Security.Permissions;
  35. using System.Reflection;
  36. namespace System.Web.Mail {
  37. /// represents a conntection to a smtp server
  38. internal class SmtpClient {
  39. private string server;
  40. private TcpClient tcpConnection;
  41. private SmtpStream smtp;
  42. private string username;
  43. private string password;
  44. private int port = 25;
  45. private bool usessl = false;
  46. private short authenticate = 1;
  47. //Initialise the variables and connect
  48. public SmtpClient( string server ) {
  49. this.server = server;
  50. Connect();
  51. }
  52. // make the actual connection
  53. // and HELO handshaking
  54. private void Connect() {
  55. tcpConnection = new TcpClient( server , port );
  56. NetworkStream stream = tcpConnection.GetStream();
  57. smtp = new SmtpStream( stream );
  58. }
  59. private void ChangeToSSLSocket( ) {
  60. #if TARGET_JVM
  61. java.lang.Class c = vmw.common.TypeUtils.ToClass( smtp.Stream );
  62. java.lang.reflect.Method m = c.getMethod("ChangeToSSLSocket", null);
  63. m.invoke(smtp.Stream, new object[]{});
  64. #else
  65. // Load Mono.Security.dll
  66. Assembly a;
  67. try {
  68. a = Assembly.Load("Consts.AssemblyMono_Security");
  69. }
  70. catch(System.IO.FileNotFoundException) {
  71. throw new SmtpException( "Cannot load Mono.Security.dll" );
  72. }
  73. Type tSslClientStream = a.GetType("Mono.Security.Protocol.Tls.SslClientStream");
  74. object[] consArgs = new object[4];
  75. consArgs[0] = smtp.Stream;
  76. consArgs[1] = server;
  77. consArgs[2] = true;
  78. Type tSecurityProtocolType = a.GetType("Mono.Security.Protocol.Tls.SecurityProtocolType");
  79. int nSsl3Val = (int) Enum.Parse(tSecurityProtocolType, "Ssl3");
  80. int nTlsVal = (int) Enum.Parse(tSecurityProtocolType, "Tls");
  81. consArgs[3] = Enum.ToObject(tSecurityProtocolType, nSsl3Val | nTlsVal);
  82. object objSslClientStream =
  83. Activator.CreateInstance(tSslClientStream, consArgs);
  84. if (objSslClientStream != null)
  85. smtp = new SmtpStream( (Stream)objSslClientStream );
  86. #endif
  87. }
  88. private void ReadFields(MailMessageWrapper msg)
  89. {
  90. string tmp;
  91. username = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/sendusername"];
  92. password = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/sendpassword"];
  93. tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"];
  94. if (tmp != null)
  95. authenticate = short.Parse(tmp);
  96. tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpusessl"];
  97. if (tmp != null)
  98. usessl = bool.Parse(tmp);
  99. tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpserverport"];
  100. if (tmp != null)
  101. port = int.Parse(tmp);
  102. }
  103. private void StartSend(MailMessageWrapper msg)
  104. {
  105. ReadFields(msg);
  106. // read the server greeting
  107. smtp.ReadResponse();
  108. smtp.CheckForStatusCode( 220 );
  109. if (usessl || (username != null && password != null && authenticate != 1))
  110. {
  111. smtp.WriteEhlo( Dns.GetHostName() );
  112. if (usessl) {
  113. bool isSSL = smtp.WriteStartTLS();
  114. if (isSSL)
  115. ChangeToSSLSocket();
  116. }
  117. if (username != null && password != null && authenticate != 1)
  118. {
  119. smtp.WriteAuthLogin();
  120. if (smtp.LastResponse.StatusCode == 334)
  121. {
  122. smtp.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(username)));
  123. smtp.ReadResponse();
  124. smtp.CheckForStatusCode(334);
  125. smtp.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(password)));
  126. smtp.ReadResponse();
  127. smtp.CheckForStatusCode(235);
  128. }
  129. }
  130. }
  131. else
  132. {
  133. smtp.WriteHelo( Dns.GetHostName() );
  134. }
  135. }
  136. public void Send( MailMessageWrapper msg ) {
  137. if( msg.From == null ) {
  138. throw new SmtpException( "From property must be set." );
  139. }
  140. if( msg.To == null ) {
  141. if( msg.To.Count < 1 ) throw new SmtpException( "Atleast one recipient must be set." );
  142. }
  143. StartSend (msg);
  144. // start with a reset incase old data
  145. // is present at the server in this session
  146. smtp.WriteRset();
  147. // write the mail from command
  148. smtp.WriteMailFrom( msg.From.Address );
  149. // write the rcpt to command for the To addresses
  150. foreach( MailAddress addr in msg.To ) {
  151. smtp.WriteRcptTo( addr.Address );
  152. }
  153. // write the rcpt to command for the Cc addresses
  154. foreach( MailAddress addr in msg.Cc ) {
  155. smtp.WriteRcptTo( addr.Address );
  156. }
  157. // write the rcpt to command for the Bcc addresses
  158. foreach( MailAddress addr in msg.Bcc ) {
  159. smtp.WriteRcptTo( addr.Address );
  160. }
  161. // write the data command and then
  162. // send the email
  163. smtp.WriteData();
  164. if( msg.Attachments.Count == 0 ) {
  165. SendSinglepartMail( msg );
  166. } else {
  167. SendMultipartMail( msg );
  168. }
  169. // write the data end tag "."
  170. smtp.WriteDataEndTag();
  171. }
  172. // sends a single part mail to the server
  173. private void SendSinglepartMail( MailMessageWrapper msg ) {
  174. // write the header
  175. smtp.WriteHeader( msg.Header );
  176. // send the mail body
  177. smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body ) );
  178. }
  179. // SECURITY-FIXME: lower assertion with imperative asserts
  180. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  181. // sends a multipart mail to the server
  182. private void SendMultipartMail( MailMessageWrapper msg ) {
  183. // generate the boundary between attachments
  184. string boundary = MailUtil.GenerateBoundary();
  185. // set the Content-Type header to multipart/mixed
  186. string bodyContentType = msg.Header.ContentType;
  187. msg.Header.ContentType =
  188. String.Format( "multipart/mixed;\r\n boundary={0}" , boundary );
  189. // write the header
  190. smtp.WriteHeader( msg.Header );
  191. // write the first part text part
  192. // before the attachments
  193. smtp.WriteBoundary( boundary );
  194. MailHeader partHeader = new MailHeader();
  195. partHeader.ContentType = bodyContentType;
  196. #if NET_1_1
  197. // Add all the custom headers to body part as specified in
  198. //Fields property of MailMessageWrapper
  199. //Remove fields specific for authenticating to SMTP server.
  200. //Need to incorporate AUTH command in SmtpStream to handle
  201. //Authorization info. Its a temporary fix for Bug no 68829.
  202. //Will dig some more on SMTP AUTH command, and then implement
  203. //Authorization. - Sanjay
  204. if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] != null)
  205. msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate");
  206. if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendusername"] != null)
  207. msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/sendusername");
  208. if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendpassword"] != null)
  209. msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/sendpassword");
  210. partHeader.Data.Add (msg.Fields.Data);
  211. #endif
  212. smtp.WriteHeader( partHeader );
  213. // FIXME: probably need to use QP or Base64 on everything higher
  214. // then 8-bit .. like utf-16
  215. smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body ) );
  216. smtp.WriteBoundary( boundary );
  217. // now start to write the attachments
  218. for( int i=0; i< msg.Attachments.Count ; i++ ) {
  219. MailAttachment a = (MailAttachment)msg.Attachments[ i ];
  220. FileInfo fileInfo = new FileInfo( a.Filename );
  221. MailHeader aHeader = new MailHeader();
  222. aHeader.ContentType =
  223. String.Format (MimeTypes.GetMimeType (fileInfo.Name) + "; name=\"{0}\"",fileInfo.Name);
  224. aHeader.ContentDisposition =
  225. String.Format( "attachment; filename=\"{0}\"" , fileInfo.Name );
  226. aHeader.ContentTransferEncoding = a.Encoding.ToString();
  227. smtp.WriteHeader( aHeader );
  228. // perform the actual writing of the file.
  229. // read from the file stream and write to the tcp stream
  230. FileStream ins = fileInfo.OpenRead ();
  231. // create an apropriate encoder
  232. IAttachmentEncoder encoder;
  233. if( a.Encoding == MailEncoding.UUEncode ) {
  234. encoder = new UUAttachmentEncoder( 644 , fileInfo.Name );
  235. } else {
  236. encoder = new Base64AttachmentEncoder();
  237. }
  238. encoder.EncodeStream( ins , smtp.Stream );
  239. ins.Close();
  240. smtp.WriteLine( "" );
  241. // if it is the last attachment write
  242. // the final boundary otherwise write
  243. // a normal one.
  244. if( i < (msg.Attachments.Count - 1) ) {
  245. smtp.WriteBoundary( boundary );
  246. } else {
  247. smtp.WriteFinalBoundary( boundary );
  248. }
  249. }
  250. }
  251. // send quit command and
  252. // closes the connection
  253. public void Close() {
  254. smtp.WriteQuit();
  255. tcpConnection.Close();
  256. }
  257. }
  258. }