File: SmtpClient.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (329 lines) | stat: -rw-r--r-- 10,075 bytes parent folder | download | duplicates (2)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//
// System.Web.Mail.SmtpClient.cs
//
// Author(s):
//   Per Arneng <pt99par@student.bth.se>
//   Sanjay Gupta <gsanjay@novell.com>
//   (C) 2004, Novell, Inc. (http://www.novell.com)
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Net.Sockets;
using System.Security.Permissions;
using System.Reflection;

namespace System.Web.Mail {

    /// represents a conntection to a smtp server
    internal class SmtpClient {
	
	private string server;
	private TcpClient tcpConnection;
	private SmtpStream smtp;
 	private string username;
 	private string password;
 	private int port = 25;
 	private bool usessl = false;
 	private short authenticate = 1;  	
        
    //Initialise the variables and connect
	public SmtpClient( string server ) {
	    
	    this.server = server;
	    Connect();
	}
	
	// make the actual connection
	// and HELO handshaking
	private void Connect() {
	    tcpConnection = new TcpClient( server , port );
	    
	    NetworkStream stream = tcpConnection.GetStream();
	    smtp = new SmtpStream( stream );
	}
	    	    
	private void ChangeToSSLSocket( ) {
#if TARGET_JVM
		java.lang.Class c = vmw.common.TypeUtils.ToClass( smtp.Stream );
		java.lang.reflect.Method m = c.getMethod("ChangeToSSLSocket", null);
		m.invoke(smtp.Stream, new object[]{});
#else
		// Load Mono.Security.dll
		Assembly a;
		try {
			a = Assembly.Load("Consts.AssemblyMono_Security");
		}
		catch(System.IO.FileNotFoundException) {
			throw new SmtpException( "Cannot load Mono.Security.dll" );
		}
		Type tSslClientStream = a.GetType("Mono.Security.Protocol.Tls.SslClientStream");
		object[] consArgs = new object[4];
		consArgs[0] = smtp.Stream;
		consArgs[1] = server;
		consArgs[2] = true;
		Type tSecurityProtocolType = a.GetType("Mono.Security.Protocol.Tls.SecurityProtocolType");
		int nSsl3Val = (int) Enum.Parse(tSecurityProtocolType, "Ssl3");
		int nTlsVal = (int) Enum.Parse(tSecurityProtocolType, "Tls");
		consArgs[3] = Enum.ToObject(tSecurityProtocolType, nSsl3Val | nTlsVal);

		object objSslClientStream = 
			Activator.CreateInstance(tSslClientStream, consArgs); 

		if (objSslClientStream != null)
			smtp = new SmtpStream( (Stream)objSslClientStream );
#endif
	}
		
	private void ReadFields(MailMessageWrapper msg)
	{
		string tmp;
		username = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/sendusername"];
		password = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/sendpassword"]; 
		tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"]; 
		if (tmp != null)
			authenticate = short.Parse(tmp);
		tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]; 	
		if (tmp != null)
			usessl = bool.Parse(tmp);
		tmp = msg.Fields.Data["http://schemas.microsoft.com/cdo/configuration/smtpserverport"]; 
		if (tmp != null)
			port = int.Parse(tmp);
	}

	private void StartSend(MailMessageWrapper msg)
	{
		ReadFields(msg);
		
		// read the server greeting
		smtp.ReadResponse();
		smtp.CheckForStatusCode( 220 );

		if (usessl || (username != null && password != null && authenticate != 1)) 
		{
			smtp.WriteEhlo( Dns.GetHostName() );

			if (usessl) {
				bool isSSL = smtp.WriteStartTLS();
				if (isSSL)
					ChangeToSSLSocket();
			}

			if (username != null && password != null && authenticate != 1) 
			{
				smtp.WriteAuthLogin();
				if (smtp.LastResponse.StatusCode == 334) 
				{
					smtp.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(username)));
					smtp.ReadResponse();
					smtp.CheckForStatusCode(334);
					smtp.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(password)));
					smtp.ReadResponse();
					smtp.CheckForStatusCode(235);
				}
			}
		}
		else 
		{
			smtp.WriteHelo( Dns.GetHostName() );
		}
	}
	
	public void Send( MailMessageWrapper msg ) {
	    
	    if( msg.From == null ) {
		throw new SmtpException( "From property must be set." );
	    }

	    if( msg.To == null ) {
		if( msg.To.Count < 1 ) throw new SmtpException( "Atleast one recipient must be set." );
	    }
	    
	    StartSend (msg);
	    // start with a reset incase old data
	    // is present at the server in this session
	    smtp.WriteRset();
	    
	    // write the mail from command
	    smtp.WriteMailFrom( msg.From.Address );
	    
	    // write the rcpt to command for the To addresses
	    foreach( MailAddress addr in msg.To ) {
		smtp.WriteRcptTo( addr.Address );
	    }

	    // write the rcpt to command for the Cc addresses
	    foreach( MailAddress addr in msg.Cc ) {
		smtp.WriteRcptTo( addr.Address );
	    }

	    // write the rcpt to command for the Bcc addresses
	    foreach( MailAddress addr in msg.Bcc ) {
		smtp.WriteRcptTo( addr.Address );
	    }
	    
	    // write the data command and then
	    // send the email
	    smtp.WriteData();
		
	    if( msg.Attachments.Count == 0 ) {
		SendSinglepartMail( msg );	    
	    } else {
		
		SendMultipartMail( msg );
	    
	    }

	    // write the data end tag "."
	    smtp.WriteDataEndTag();

	}
	
	// sends a single part mail to the server
	private void SendSinglepartMail( MailMessageWrapper msg ) {
	    	    	    
	    // write the header
	    smtp.WriteHeader( msg.Header );
	    
	    // send the mail body
	    smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body ) );

	}

	// SECURITY-FIXME: lower assertion with imperative asserts	
	[FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
	// sends a multipart mail to the server
	private void SendMultipartMail( MailMessageWrapper msg ) {
	    	    
	    // generate the boundary between attachments
	    string boundary = MailUtil.GenerateBoundary();
		
	    // set the Content-Type header to multipart/mixed
	    string bodyContentType = msg.Header.ContentType;

	    msg.Header.ContentType = 
		String.Format( "multipart/mixed;\r\n   boundary={0}" , boundary );
		
	    // write the header
	    smtp.WriteHeader( msg.Header );
		
	    // write the first part text part
	    // before the attachments
	    smtp.WriteBoundary( boundary );
		
	    MailHeader partHeader = new MailHeader();
	    partHeader.ContentType = bodyContentType;		

#if NET_1_1
		// Add all the custom headers to body part as specified in 
		//Fields property of MailMessageWrapper

        //Remove fields specific for authenticating to SMTP server.
        //Need to incorporate AUTH command in SmtpStream to handle  
        //Authorization info. Its a temporary fix for Bug no 68829.
        //Will dig some more on SMTP AUTH command, and then implement
        //Authorization. - Sanjay

        if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] != null)
            msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate");
        if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendusername"] != null)
            msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/sendusername");
        if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendpassword"] != null)
            msg.Fields.Data.Remove ("http://schemas.microsoft.com/cdo/configuration/sendpassword");
		partHeader.Data.Add (msg.Fields.Data);
#endif

	    smtp.WriteHeader( partHeader );
	  
	    // FIXME: probably need to use QP or Base64 on everything higher
	    // then 8-bit .. like utf-16
	    smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body )  );

	    smtp.WriteBoundary( boundary );

	    // now start to write the attachments
	    
	    for( int i=0; i< msg.Attachments.Count ; i++ ) {
		MailAttachment a = (MailAttachment)msg.Attachments[ i ];
			
		FileInfo fileInfo = new FileInfo( a.Filename );

		MailHeader aHeader = new MailHeader();
		
		aHeader.ContentType = 
		    String.Format (MimeTypes.GetMimeType (fileInfo.Name) + "; name=\"{0}\"",fileInfo.Name);
		
		aHeader.ContentDisposition = 
		    String.Format( "attachment; filename=\"{0}\"" , fileInfo.Name );
		
		aHeader.ContentTransferEncoding = a.Encoding.ToString();
		    		
		smtp.WriteHeader( aHeader );
		   
		// perform the actual writing of the file.
		// read from the file stream and write to the tcp stream
		FileStream ins = fileInfo.OpenRead ();
		
		// create an apropriate encoder
		IAttachmentEncoder encoder;
		if( a.Encoding == MailEncoding.UUEncode ) {
		    encoder = new UUAttachmentEncoder( 644 , fileInfo.Name  );
		} else {
		    encoder = new Base64AttachmentEncoder();
		}
		
		encoder.EncodeStream( ins , smtp.Stream );
		
		ins.Close();
		
		    
		smtp.WriteLine( "" );
		
		// if it is the last attachment write
		// the final boundary otherwise write
		// a normal one.
		if( i < (msg.Attachments.Count - 1) ) { 
		    smtp.WriteBoundary( boundary );
		} else {
		    smtp.WriteFinalBoundary( boundary );
		}
		    
	    }
	       
	}
	
	// send quit command and
	// closes the connection
	public void Close() {
	    
	    smtp.WriteQuit();
	    tcpConnection.Close();
	
	}
	
		
    }
}