SmtpClient.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. //
  2. // System.Net.Mail.SmtpClient.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2004
  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. #if NET_2_0
  30. using System;
  31. using System.Collections.Generic;
  32. using System.ComponentModel;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Mime;
  36. using System.Net.Sockets;
  37. using System.Security.Cryptography.X509Certificates;
  38. using System.Text;
  39. using System.Threading;
  40. namespace System.Net.Mail {
  41. public class SmtpClient
  42. {
  43. #region Fields
  44. string host;
  45. int port;
  46. int timeout = 100000;
  47. ICredentialsByHost credentials;
  48. bool useDefaultCredentials;
  49. string pickupDirectoryLocation;
  50. SmtpDeliveryMethod deliveryMethod;
  51. bool enableSsl;
  52. X509CertificateCollection clientCertificates;
  53. TcpClient client;
  54. NetworkStream stream;
  55. StreamWriter writer;
  56. StreamReader reader;
  57. int boundaryIndex;
  58. Mutex mutex = new Mutex ();
  59. const string MimeVersion = "1.0 (produced by Mono System.Net.Mail.SmtpClient)";
  60. #endregion // Fields
  61. #region Constructors
  62. public SmtpClient ()
  63. : this (null, 0)
  64. {
  65. }
  66. public SmtpClient (string host)
  67. : this (host, 0)
  68. {
  69. }
  70. [MonoTODO ("Load default settings from configuration.")]
  71. public SmtpClient (string host, int port)
  72. {
  73. // FIXME: load from configuration
  74. if (String.IsNullOrEmpty (host))
  75. Host = "127.0.0.1";
  76. else
  77. Host = host;
  78. // FIXME: load from configuration
  79. if (port == 0)
  80. Port = 25;
  81. else
  82. Port = port;
  83. // FIXME: load credentials from configuration
  84. }
  85. #endregion // Constructors
  86. #region Properties
  87. [MonoTODO]
  88. public X509CertificateCollection ClientCertificates {
  89. get { return clientCertificates; }
  90. }
  91. public ICredentialsByHost Credentials {
  92. get { return credentials; }
  93. set { credentials = value; }
  94. }
  95. public SmtpDeliveryMethod DeliveryMethod {
  96. get { return deliveryMethod; }
  97. set { deliveryMethod = value; }
  98. }
  99. public bool EnableSsl {
  100. get { return enableSsl; }
  101. set { enableSsl = value; }
  102. }
  103. public string Host {
  104. get { return host; }
  105. [MonoTODO ("Check to make sure an email is not being sent.")]
  106. set {
  107. if (value == null)
  108. throw new ArgumentNullException ();
  109. if (value.Length == 0)
  110. throw new ArgumentException ();
  111. host = value;
  112. }
  113. }
  114. public string PickupDirectoryLocation {
  115. get { return pickupDirectoryLocation; }
  116. set { pickupDirectoryLocation = value; }
  117. }
  118. public int Port {
  119. get { return port; }
  120. [MonoTODO ("Check to make sure an email is not being sent.")]
  121. set {
  122. if (value <= 0)
  123. throw new ArgumentOutOfRangeException ();
  124. port = value;
  125. }
  126. }
  127. [MonoTODO]
  128. public ServicePoint ServicePoint {
  129. get { throw new NotImplementedException (); }
  130. }
  131. public int Timeout {
  132. get { return timeout; }
  133. [MonoTODO ("Check to make sure an email is not being sent.")]
  134. set {
  135. if (value < 0)
  136. throw new ArgumentOutOfRangeException ();
  137. timeout = value;
  138. }
  139. }
  140. [MonoTODO]
  141. public bool UseDefaultCredentials {
  142. get { return useDefaultCredentials; }
  143. set { useDefaultCredentials = value; }
  144. }
  145. #endregion // Properties
  146. #region Events
  147. public event SendCompletedEventHandler SendCompleted;
  148. #endregion // Events
  149. #region Methods
  150. private void EndSection (string section)
  151. {
  152. SendData (String.Format ("--{0}--", section));
  153. }
  154. private string GenerateBoundary ()
  155. {
  156. string output = GenerateBoundary (boundaryIndex);
  157. boundaryIndex += 1;
  158. return output;
  159. }
  160. private static string GenerateBoundary (int index)
  161. {
  162. return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
  163. }
  164. private bool IsError (SmtpResponse status)
  165. {
  166. return ((int) status.StatusCode) >= 400;
  167. }
  168. protected void OnSendCompleted (AsyncCompletedEventArgs e)
  169. {
  170. if (SendCompleted != null)
  171. SendCompleted (this, e);
  172. }
  173. private SmtpResponse Read ()
  174. {
  175. SmtpResponse response;
  176. char[] buf = new char [3];
  177. reader.Read (buf, 0, 3);
  178. reader.Read ();
  179. response.StatusCode = (SmtpStatusCode) Int32.Parse (new String (buf));
  180. response.Description = reader.ReadLine ();
  181. return response;
  182. }
  183. [MonoTODO ("Need to work on message attachments.")]
  184. public void Send (MailMessage message)
  185. {
  186. // Block while sending
  187. mutex.WaitOne ();
  188. SmtpResponse status;
  189. client = new TcpClient (host, port);
  190. stream = client.GetStream ();
  191. writer = new StreamWriter (stream);
  192. reader = new StreamReader (stream);
  193. boundaryIndex = 0;
  194. string boundary = GenerateBoundary ();
  195. bool hasAlternateViews = (message.AlternateViews.Count > 0);
  196. bool hasAttachments = (message.Attachments.Count > 0);
  197. status = Read ();
  198. if (IsError (status))
  199. throw new SmtpException (status.StatusCode);
  200. // HELO
  201. status = SendCommand (Command.Helo, Dns.GetHostName ());
  202. if (IsError (status))
  203. throw new SmtpException (status.StatusCode);
  204. // MAIL FROM:
  205. status = SendCommand (Command.MailFrom, message.From.Address);
  206. if (IsError (status))
  207. throw new SmtpException (status.StatusCode);
  208. // Send RCPT TO: for all recipients
  209. List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
  210. for (int i = 0; i < message.To.Count; i ++) {
  211. status = SendCommand (Command.RcptTo, message.To [i].Address);
  212. if (IsError (status))
  213. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address.ToString ()));
  214. }
  215. for (int i = 0; i < message.CC.Count; i ++) {
  216. status = SendCommand (Command.RcptTo, message.CC [i].Address);
  217. if (IsError (status))
  218. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address.ToString ()));
  219. }
  220. for (int i = 0; i < message.Bcc.Count; i ++) {
  221. status = SendCommand (Command.RcptTo, message.Bcc [i].Address);
  222. if (IsError (status))
  223. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address.ToString ()));
  224. }
  225. if (sfre.Count > 0)
  226. throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
  227. // DATA
  228. status = SendCommand (Command.Data);
  229. if (IsError (status))
  230. throw new SmtpException (status.StatusCode);
  231. // Figure out the message content type
  232. ContentType messageContentType = message.BodyContentType;
  233. if (hasAttachments || hasAlternateViews) {
  234. messageContentType.Boundary = boundary;
  235. if (hasAttachments)
  236. messageContentType.MediaType = "multipart/mixed";
  237. else
  238. messageContentType.MediaType = "multipart/alternative";
  239. }
  240. // Send message headers
  241. SendHeader (HeaderName.From, message.From.ToString ());
  242. SendHeader (HeaderName.To, message.To.ToString ());
  243. if (message.CC.Count > 0)
  244. SendHeader (HeaderName.Cc, message.CC.ToString ());
  245. if (message.Bcc.Count > 0)
  246. SendHeader (HeaderName.Bcc, message.Bcc.ToString ());
  247. SendHeader (HeaderName.Subject, message.Subject);
  248. foreach (string s in message.Headers.AllKeys)
  249. SendHeader (s, message.Headers [s]);
  250. SendHeader ("Content-Type", messageContentType.ToString ());
  251. SendData ("");
  252. if (hasAlternateViews) {
  253. string innerBoundary = boundary;
  254. // The body is *technically* an alternative view. The body text goes FIRST because
  255. // that is most compatible with non-MIME readers.
  256. //
  257. // If there are attachments, then the main content-type is multipart/mixed and
  258. // the subpart has type multipart/alternative. Then all of the views have their
  259. // own types.
  260. //
  261. // If there are no attachments, then the main content-type is multipart/alternative
  262. // and we don't need this subpart.
  263. if (hasAttachments) {
  264. innerBoundary = GenerateBoundary ();
  265. ContentType contentType = new ContentType ("multipart/alternative");
  266. contentType.Boundary = innerBoundary;
  267. StartSection (boundary, contentType);
  268. }
  269. // Start the section for the body text. This is either section "1" or "0" depending
  270. // on whether there are attachments.
  271. StartSection (innerBoundary, messageContentType, TransferEncoding.QuotedPrintable);
  272. SendData (message.Body);
  273. // Send message attachments.
  274. SendAttachments (message.Attachments, innerBoundary);
  275. if (hasAttachments)
  276. EndSection (innerBoundary);
  277. }
  278. else {
  279. // If this is multipart then we need to send a boundary before the body.
  280. if (hasAttachments) {
  281. // FIXME: check this
  282. ContentType contentType = new ContentType ("multipart/alternative");
  283. StartSection (boundary, contentType, TransferEncoding.QuotedPrintable);
  284. }
  285. SendData (message.Body);
  286. }
  287. // Send attachments
  288. if (hasAttachments) {
  289. string innerBoundary = boundary;
  290. // If we have alternate views and attachments then we need to nest this part inside another
  291. // boundary. Otherwise, we are cool with the boundary we have.
  292. if (hasAlternateViews) {
  293. innerBoundary = GenerateBoundary ();
  294. ContentType contentType = new ContentType ("multipart/mixed");
  295. contentType.Boundary = innerBoundary;
  296. StartSection (boundary, contentType);
  297. }
  298. SendAttachments (message.Attachments, innerBoundary);
  299. if (hasAlternateViews)
  300. EndSection (innerBoundary);
  301. }
  302. SendData (".");
  303. status = Read ();
  304. if (IsError (status))
  305. throw new SmtpException (status.StatusCode);
  306. status = SendCommand (Command.Quit);
  307. writer.Close ();
  308. reader.Close ();
  309. stream.Close ();
  310. client.Close ();
  311. // Release the mutex to allow other threads access
  312. mutex.ReleaseMutex ();
  313. }
  314. public void Send (string from, string to, string subject, string body)
  315. {
  316. Send (new MailMessage (from, to, subject, body));
  317. }
  318. private void SendData (string data)
  319. {
  320. writer.WriteLine (data);
  321. writer.Flush ();
  322. }
  323. [MonoTODO]
  324. public void SendAsync (MailMessage message, object userToken)
  325. {
  326. Send (message);
  327. OnSendCompleted (new AsyncCompletedEventArgs (null, false, userToken));
  328. }
  329. public void SendAsync (string from, string to, string subject, string body, object userToken)
  330. {
  331. SendAsync (new MailMessage (from, to, subject, body), userToken);
  332. }
  333. [MonoTODO]
  334. public void SendAsyncCancel ()
  335. {
  336. throw new NotImplementedException ();
  337. }
  338. private void SendAttachments (AttachmentCollection attachments, string boundary)
  339. {
  340. for (int i = 0; i < attachments.Count; i += 1) {
  341. // FIXME: check this
  342. ContentType contentType = new ContentType ("multipart/alternative");
  343. StartSection (boundary, contentType, attachments [i].TransferEncoding);
  344. switch (attachments [i].TransferEncoding) {
  345. case TransferEncoding.Base64:
  346. byte[] content = new byte [attachments [i].ContentStream.Length];
  347. attachments [i].ContentStream.Read (content, 0, content.Length);
  348. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  349. break;
  350. case TransferEncoding.QuotedPrintable:
  351. StreamReader sr = new StreamReader (attachments [i].ContentStream);
  352. SendData (ToQuotedPrintable (sr.ReadToEnd ()));
  353. break;
  354. //case TransferEncoding.SevenBit:
  355. //case TransferEncoding.Unknown:
  356. default:
  357. SendData ("TO BE IMPLEMENTED");
  358. break;
  359. }
  360. }
  361. }
  362. private SmtpResponse SendCommand (string command, string data)
  363. {
  364. writer.Write (command);
  365. writer.Write (" ");
  366. SendData (data);
  367. return Read ();
  368. }
  369. private SmtpResponse SendCommand (string command)
  370. {
  371. writer.WriteLine (command);
  372. writer.Flush ();
  373. return Read ();
  374. }
  375. private void SendHeader (string name, string value)
  376. {
  377. SendData (String.Format ("{0}: {1}", name, value));
  378. }
  379. private void StartSection (string section, ContentType sectionContentType)
  380. {
  381. SendData (String.Format ("--{0}", section));
  382. SendHeader ("content-type", sectionContentType.ToString ());
  383. SendData ("");
  384. }
  385. private void StartSection (string section, ContentType sectionContentType,TransferEncoding transferEncoding)
  386. {
  387. SendData (String.Format ("--{0}", section));
  388. SendHeader ("content-type", sectionContentType.ToString ());
  389. SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
  390. SendData ("");
  391. }
  392. private string ToQuotedPrintable (string input)
  393. {
  394. StringReader reader = new StringReader (input);
  395. StringWriter writer = new StringWriter ();
  396. int i;
  397. while ((i = reader.Read ()) > 0) {
  398. if (i > 127) {
  399. writer.Write ("=");
  400. writer.Write (Convert.ToString (i, 16).ToUpper ());
  401. }
  402. else
  403. writer.Write (Convert.ToChar (i));
  404. }
  405. return writer.GetStringBuilder ().ToString ();
  406. }
  407. private static string GetTransferEncodingName (TransferEncoding encoding)
  408. {
  409. switch (encoding) {
  410. case TransferEncoding.QuotedPrintable:
  411. return "quoted-printable";
  412. case TransferEncoding.SevenBit:
  413. return "7bit";
  414. case TransferEncoding.Base64:
  415. return "base64";
  416. }
  417. return "unknown";
  418. }
  419. /*
  420. [MonoTODO]
  421. private sealed ContextAwareResult IGetContextAwareResult.GetContextAwareResult ()
  422. {
  423. throw new NotImplementedException ();
  424. }
  425. */
  426. #endregion // Methods
  427. // The Command struct is used to store constant string values representing SMTP commands.
  428. private struct Command {
  429. public const string Data = "DATA";
  430. public const string Helo = "HELO";
  431. public const string MailFrom = "MAIL FROM:";
  432. public const string Quit = "QUIT";
  433. public const string RcptTo = "RCPT TO:";
  434. }
  435. // The HeaderName struct is used to store constant string values representing mail headers.
  436. private struct HeaderName {
  437. public const string ContentTransferEncoding = "Content-Transfer-Encoding";
  438. public const string ContentType = "Content-Type";
  439. public const string Bcc = "Bcc";
  440. public const string Cc = "Cc";
  441. public const string From = "From";
  442. public const string Subject = "Subject";
  443. public const string To = "To";
  444. public const string MimeVersion = "MIME-Version";
  445. public const string MessageId = "Message-ID";
  446. }
  447. // This object encapsulates the status code and description of an SMTP response.
  448. private struct SmtpResponse {
  449. public SmtpStatusCode StatusCode;
  450. public string Description;
  451. }
  452. }
  453. }
  454. #endif // NET_2_0