SmtpClient.cs 14 KB

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