public void TestSend() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			//emailmessage.FromAddress=new EmailAddress("*****@*****.**", "Bridge, Mike");
			//emailmessage.FromAddress=new EmailAddress("*****@*****.**", "<Mike Bridge>");

			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test HTML and Text";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			emailmessage.BodyText="This is a test";

			emailmessage.AddCustomHeader("X-MyHeader1", "my header number one");
			//emailmessage.AddCustomHeader("Sender", TestAddressHelper.GetToAddress().ToString());

			Log4netLogger logger=new Log4netLogger();
			_smtpserver.LogSmtpWrite+=(new SmtpServer.LogHandler(logger.Log));
			_smtpserver.LogSmtpReceive+=(new SmtpServer.LogHandler(logger.Log));
			_smtpserver.LogSmtpCompleted+=(new SmtpServer.LogHandler(logger.Log));
			
			emailmessage.Send(_smtpserver);

		

		}
        public override void Send()
        {
            EmailMessage msg = new EmailMessage();
            foreach(string addr in AddressesFromList(To))
                msg.AddToAddress(addr);

            msg.FromAddress = new EmailAddress(From);
            msg.Subject = Subject;
            if(TextBody != null) msg.TextPart = new TextAttachment(TextBody);
            if(HtmlBody != null) msg.HtmlPart = new HtmlAttachment(HtmlBody);

            SmtpServer server = new SmtpServer(SmtpHost, SmtpServerPort);

            switch (SmtpAuthType)
            {
                case "BASIC":
                    log.Info("BASIC authentication was added to SMTP request");
                    SmtpAuthToken at = new SmtpAuthToken(SmtpAuthUsername, SmtpAuthPassword);
                    server.SmtpAuthToken = at;
                    break;
                default:
                    // no authentication
                    break;
            }

            log.Info(string.Format("Sending mail to {0} from {1} with subject {2}", msg.ToAddresses, msg.FromAddress, msg.Subject));
            msg.Send(server);
            log.Info("Sent mail");
        }
Esempio n. 3
0
        /// <summary>
        /// Sends an email with the specified parameters.
        /// </summary>
        /// <param name="to">Email address of the recipient.</param>
        /// <param name="from">Email address of the sender.</param>
        /// <param name="subject">Subject of the email.</param>
        /// <param name="message">The body of the email Message.</param>
        /// <returns></returns>
        public override bool Send(string to, string from, string subject, string message)
        {
            EmailMessage email = new EmailMessage();
            email.FromAddress = new EmailAddress(from);
            email.AddToAddress(new EmailAddress(to));
            email.Subject = subject;
            email.BodyText = message;

            SmtpServer smtpServer = new SmtpServer(SmtpServer, Port);

            //Authentication.
            if(this.UserName != null && this.Password != null)
            {
                smtpServer.SmtpAuthToken = new SmtpAuthToken(UserName, Password);
            }

            try
            {
                return email.Send(smtpServer);
            }
            //Mail Exception is thrown when there are network or connection errors
            catch(MailException mailEx)
            {
                string msg = String.Format("Connection or network error sending email from {0} to {1}", from, to);
                Log.Error(msg, mailEx);
            }
            //SmtpException is thrown for all SMTP exceptions
            catch (SmtpException smtpEx)
            {
                string msg = String.Format("Error sending email from {0} to {1}", from, to);
                Log.Error(msg, smtpEx);
            }
            return false;
        }
		public void TestTwo() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="A photo of hawthornes";
	
			emailmessage.TextPart=new TextAttachment("This photo requires a better email reader.");		
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+
				"<p>Note to self: look at this photo again in 30 years.</p>"+
				"<p><img src=\"cid:hawthornes\" alt=\"Hawthorne bush\"/></p>"+
				"<p>-Marcel</p>");
			
			FileInfo relatedfileinfo=new FileInfo(@"..\..\TestFiles\grover.jpg");
	
			FileAttachment relatedfileattachment=new FileAttachment(relatedfileinfo,"hawthornes");
	
			relatedfileattachment.ContentType="image/jpeg";
			
			emailmessage.AddRelatedAttachment(relatedfileattachment);
			
			SmtpServer smtpserver=TestAddressHelper.GetSmtpServer();
			emailmessage.Send(smtpserver);
			//Assert.IsNull(smtpserver.GetSmtpConversation());
		}
		public void TestOne() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="Missed you";
	
			emailmessage.TextPart=new TextAttachment("Just checking where "+
				"you were last night.\r\nSend me a note!\r\n\r\n-Charles");
		
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+
				"<p>Just checking up on where you were last night.</p>\r\n"+
				"<p>Send me a note!</p>\r\n\r\n"+
				"<p>-Charles</p></body></html>");
		
			SmtpServer smtpserver=TestAddressHelper.GetSmtpServer();
			//smtpserver.CaptureSmtpConversation=true;

			try 
			{
				emailmessage.Send(smtpserver);		
				
			}
			finally 
			{
				//log.Debug(smtpserver.GetSmtpConversation());
				//Assert.IsNotNull(smtpserver.GetSmtpConversation());
				//smtpserver.CaptureSmtpConversation=false;	
			}
		}
Esempio n. 6
0
        private void StartThread()
        {
            try
            {
                EmailMessage message=new EmailMessage();

                message.Subject=_subject;
                message.FromAddress=_fromaddress;

                EmailAddress[] toaddresses=_toaddresses;

                for (int i=0; i<toaddresses.Length; i++)
                {
                    message.AddToAddress(toaddresses[i]);
                }

                if (this._envelopefrom!=null)
                {
                    message.EnvelopeFromAddress=_envelopefrom;
                }
                bool hashtml=false;
                if (_htmlcontent!=null && _htmlcontent.Trim()!="")
                {
                    hashtml=true;
                    message.HtmlPart=new HtmlAttachment(_htmlcontent);
                }

                if (_textcontent!=null && _textcontent.Trim()!="")
                {
                    if (hashtml)
                    {
                        message.TextPart=new TextAttachment(_textcontent);
                    }
                    else
                    {
                        message.BodyText=_textcontent;
                    }
                }
                //			LogWindow logwindow=new LogWindow();
                //			logwindow.ShowDialog(this);

                _smtpserver.LogSmtpWrite+=new SmtpServer.LogHandler(_logwindow.LogSmtpWrite);

                _smtpserver.LogSmtpReceive+=new SmtpServer.LogHandler(_logwindow.LogSmtpReceive);

                _smtpserver.LogSmtpCompleted+=new SmtpServer.LogHandler(_logwindow.LogSmtpCompleted);

                _logwindow.LogInfo("Sending to "+_smtpserver.ToString()+"\r\n");
                message.Send(_smtpserver);
            }
            catch (Exception ex)
            {
                _logwindow.LogError(ex.Message+"\r\n");
            }
        }
		private EmailMessage GetTestHtmlAndTextMessage() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test HTML and Text";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			emailmessage.AddCustomHeader("X-MyHeader1", "my header number one");
			emailmessage.AddCustomHeader("X-MyHeader2", "my header number two");

			return emailmessage;
		}
		public void TestBasicSend() 
		{
			

			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests TestBasicSend";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");
			emailmessage.EnvelopeFromAddress=new EmailAddress("*****@*****.**");
			emailmessage.Send(_smtpserver);
			// this doesn't test anything yet
		}
		public void TestWindows1251() {

			EmailMessage emailmessage = new EmailMessage();
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());

			emailmessage.Subject = "ошибочка?";
			emailmessage.HeaderCharSet = System.Text.Encoding.GetEncoding("windows-1251");

			TextAttachment ta = new TextAttachment("\r\nнесколько строк по русски");
			ta.CharSet = System.Text.Encoding.GetEncoding("windows-1251");
			emailmessage.TextPart = ta;
			emailmessage.Send(TestAddressHelper.GetSmtpServer());
			Assert.IsTrue(emailmessage.ToDataString().IndexOf("Subject: =?windows-1251") > 0, "Missing windows-1251 in subject");
			Assert.IsTrue(emailmessage.ToDataString().IndexOf("koi8-r") < 0);
		}
		public void TestEmailWithDot() 
		{
			//SmtpServer smtpserver=TestAddressHelper.GetSmtpServer();

			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test Dot";
			emailmessage.TextPart=new TextAttachment("This\r\n.is the\r\n..text\r\n...part.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\n..is the<br>\r\n..<strong>HTML</strong><br>\r\npart.</body></html>");
			emailmessage.Send(_smtpserver);

			// this doesn't test anything yet
			//log.Debug("MESSAGE: "+emailmessage.ToDataString());

		}
		public void TestFileFromStream() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="Here's your license";
	
			emailmessage.TextPart=new TextAttachment("This is a license.\r\n\r\n"+
				"We will spend your money on a new plasma TV.");
		
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+
				"<p>This is a license.</p>\r\n"+
				"<p>We will spend your money on a new <i>plasma TV</i>.</p>\r\n"+
				"</body></html>");
		
			MemoryStream stream=new MemoryStream();
			StreamWriter sw=new StreamWriter(stream);
			sw.WriteLine("this is some test data 1");
			sw.WriteLine("this is some test data 2");
			sw.WriteLine("this is some test data 3");
			sw.WriteLine("this is some test data 4");
			sw.Flush();
			stream.Seek(0, SeekOrigin.Begin);

			//BinaryReader br=new BinaryReader(stream);

			FileAttachment fileAttachment=new FileAttachment(new StreamReader(stream));
			
			//fileAttachment.ContentType
			fileAttachment.FileName="License.txt";
			fileAttachment.CharSet=System.Text.Encoding.ASCII;
			fileAttachment.ContentType="text/plain";
			emailmessage.AddMixedAttachment(fileAttachment);
			
			//emailmessage.Send(TestAddressHelper.GetSmtpServer());		
		}
		public void TestThree() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
	
			emailmessage.Subject="Something has come up";
	
			emailmessage.TextPart=new TextAttachment("I regret that something has "+
				"come up unexpectedly,\r\n"+
				"and I must postpone our meeting.\r\n\r\n"+	
				"Please read the 20 pages of my thoughts on this in the attached\r\n"+
				"PDF file.\r\n\r\n-Marcel");
		
			emailmessage.HtmlPart=new HtmlAttachment("<p>I regret that something "+
				"has come up unexpectedly,\r\n"+
				"and I must postpone our meeting.</p>\r\n"+	
				"<p>Please read the 20 pages of my thoughts on this in the attached\r\n"+
				"PDF file.</p>\r\n<p>-Marcel</p>");
			
			FileAttachment fileattachment=new FileAttachment(new FileInfo(@"..\..\TestFiles\grover.jpg"));
	
			fileattachment.ContentType="image/jpeg";
			
			emailmessage.AddMixedAttachment(fileattachment);
		
			emailmessage.Send(TestAddressHelper.GetSmtpServer());
	
		}
		public void TestJapaneseHtmlAndTextB64Encoding() 
		{
			//SmtpServer smtpserver=TestAddressHelper.GetSmtpServer();
			System.Text.Encoding encoding=System.Text.Encoding.GetEncoding("Shift_JIS");

			EmailAddress japanesefromaddress=new EmailAddress(TestAddressHelper.GetFromAddress().Email, "日本語", EncodingType.Base64, encoding);
			EmailAddress japanesetoaddress=new EmailAddress(TestAddressHelper.GetToAddress().Email, "日本語", EncodingType.Base64, encoding);
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.HeaderEncoding=DotNetOpenMail.Encoding.EncodingType.Base64;
			emailmessage.HeaderCharSet=System.Text.Encoding.GetEncoding("Shift_JIS");

			emailmessage.FromAddress=japanesefromaddress;
			emailmessage.AddToAddress(japanesetoaddress);
			emailmessage.Subject="日本語 - Base 64";
			emailmessage.TextPart=new TextAttachment("東京、日本語");
			
			emailmessage.TextPart.CharSet=System.Text.Encoding.GetEncoding("Shift_JIS");
			emailmessage.TextPart.Encoding=DotNetOpenMail.Encoding.EncodingType.Base64;
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>東京、日本語</body></html>");
			
			emailmessage.HtmlPart.CharSet=System.Text.Encoding.GetEncoding("Shift_JIS");
			emailmessage.HtmlPart.Encoding=DotNetOpenMail.Encoding.EncodingType.Base64;

			emailmessage.Send(_smtpserver);

			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			log.Debug(content);

			int i=0;
			String line=null;


			bool toHeaderEncoded=false;
			bool fromHeaderEncoded=false;
			bool subjectHeaderEncoded=false;
			//bool htmlEncoded=false;
			//bool textEncoded=false;
			bool hasPlainText=false;
			bool hasHtmlText=false;

			
			
			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				//log.Debug("FOUND +ACIAKw-line);
				if (line.IndexOf("To: =?iso-2022-jp?B?k/qWe4zq?= <"+japanesetoaddress.Email+">")==0)
				{					
					toHeaderEncoded=true;
				}
				if (line.IndexOf("From") == 0) 
				{
					String expectedfrom="From: =?iso-2022-jp?B?k/qWe4zq?= <"+japanesefromaddress.Email+">";
					if (line.IndexOf(expectedfrom)== 0) 
					{
						fromHeaderEncoded=true;
					}
				}
				if (line.IndexOf("Subject: =?iso-2022-jp?B?k/qWe4zqIC0gQmFzZSA2NA==?=")==0)
				{
					subjectHeaderEncoded=true;
				}
				if (line.IndexOf("Content-Type: multipart/alternative")==0)
				{
					//htmlEncoded=true;
				}
				if (line.IndexOf("Content-Type: text/html")==0)
				{
					hasHtmlText=true;
				}
				if (line.IndexOf("Content-Type: text/plain")==0)
				{
					hasPlainText=true;
				}
				if (line.IndexOf("X-Mailer: DotNetOpenMail " + VersionInfo.GetInstance().ToString())==0)
				{
					//hasDefaultXMailerHeader=true;
				}
				if (line.IndexOf("X-MyHeader1: my header number one") == 0)
				{
					//hasCustomHeader1=true;
				}
				if (line.IndexOf("X-MyHeader2: my header number two") == 0)
				{
					//hasCustomHeader2=true;
				}

				// log.Debug("Line +ACIAKw-i+-": +ACIAKw-line);				
			}
			Assert.IsTrue(toHeaderEncoded, "To Header not encoded");
			Assert.IsTrue(fromHeaderEncoded, "From Header not encoded");
			Assert.IsTrue(subjectHeaderEncoded, "Subject Header not encoded");
			//Assert.IsTrue(hasSubjectHeader, "Missing Subject Header");
			//Assert.IsTrue(hasMimeVersion, "Missing Mime Version header");
			//Assert.IsTrue(hasMultipartAlternative, "Missing Mime Multipart/Alternative setting");
			Assert.IsTrue(hasPlainText, "Missing Plain Text");
			Assert.IsTrue(hasHtmlText, "Missing HTML");
			//Assert.IsTrue(htmlEncoded, "HTML Not encoded");
			//Assert.IsTrue(textEncoded, "Text Not encoded");
			//Assert.IsTrue(hasDefaultXMailerHeader, "Missing X-Mailer Header");
			//Assert.IsTrue(hasCustomHeader1, "Missing Custom Header 1");
			//Assert.IsTrue(hasCustomHeader2, "Missing Custom Header 2");
			//Assert.AreEqual(2, quotedPrintableParts, "Expected 2 quoted printable declarations, found +ACIAKw-quotedPrintableParts);
		
			


		}
		public void TestJapaneseHtmlAndTextQPEncoding() 
		{
			//SmtpServer smtpserver=TestAddressHelper.GetSmtpServer();
			System.Text.Encoding encoding=System.Text.Encoding.GetEncoding("Shift_JIS");

			EmailAddress japanesefromaddress=new EmailAddress(TestAddressHelper.GetFromAddress().Email, "日本語", EncodingType.QuotedPrintable, encoding);
			EmailAddress japanesetoaddress=new EmailAddress(TestAddressHelper.GetToAddress().Email, "日本語", EncodingType.QuotedPrintable, encoding);
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.HeaderEncoding=DotNetOpenMail.Encoding.EncodingType.QuotedPrintable;
			System.Text.Encoding jencoding=System.Text.Encoding.GetEncoding("iso-2022-jp");
			//emailmessage.HeaderCharSet=System.Text.Encoding.GetEncoding("Shift_JIS");
			emailmessage.HeaderCharSet=jencoding;
			
			log.Debug("ENCODING IS "+jencoding.EncodingName);
			log.Debug("IN HEADER:"+jencoding.HeaderName);
			log.Debug("IN BODY:"+jencoding.BodyName);
			log.Debug("CODE PAGE:"+jencoding.CodePage);
			log.Debug("WebName:"+jencoding.WebName);
			log.Debug("WINDOWS CODE PAGE:"+jencoding.WindowsCodePage);
			emailmessage.FromAddress=japanesefromaddress;
			emailmessage.AddToAddress(japanesetoaddress);
			emailmessage.Subject="日本語 - Quoted Printable";
			emailmessage.TextPart=new TextAttachment("東京、日本語");
			//emailmessage.TextPart.CharSet+AD0AIg-Shift_JIS+ACIAOw-
			emailmessage.TextPart.CharSet=jencoding;
			emailmessage.TextPart.Encoding=DotNetOpenMail.Encoding.EncodingType.QuotedPrintable;
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>東京、日本語</body></html>");
			//emailmessage.HtmlPart.CharSet+AD0AIg-Shift_JIS+ACIAOw-
			emailmessage.HtmlPart.CharSet=jencoding;
			emailmessage.HtmlPart.Encoding=DotNetOpenMail.Encoding.EncodingType.QuotedPrintable;

			emailmessage.Send(_smtpserver);

			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			log.Debug(content);

			int i=0;
			String line=null;


			bool toHeaderEncoded=false;
			bool fromHeaderEncoded=false;
			bool subjectHeaderEncoded=false;
			bool htmlEncoded=false;
			bool textEncoded=false;
			bool hasPlainText=false;
			bool hasHtmlText=false;

			
			
			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				//log.Debug("FOUND +ACIAKw-line);
				if (line.IndexOf("To: =?iso-2022-jp?Q?=93=FA=96{=8C=EA?= <"+japanesetoaddress.Email+">")==0)
				{					
					toHeaderEncoded=true;
				}
				if (line.IndexOf("From") == 0) 
				{
					String expectedfrom="From: =?iso-2022-jp?Q?=93=FA=96{=8C=EA?= <"+japanesefromaddress.Email+">";

					if (line.IndexOf(expectedfrom)== 0) 
					{
						fromHeaderEncoded=true;
					}
				}
				if (line.IndexOf("Subject: =?iso-2022-jp?Q?=1B$BF|K\\8l=1B(B=20-=20Quoted=20Printable?=")==0)
				{
					subjectHeaderEncoded=true;
				}
				if (line.IndexOf("<html><body>=1B$BEl5~!\"F|K\\8l=1B(B</body></html>")==0)
				{
					//<html><body>=67=71=4E=AC=30=01=65=E5=67=2C=8A=9E</body></html>

					htmlEncoded=true;
				}
				if (line.IndexOf("=1B$BEl5~!\"F|K\\8l=1B(B")==0)
				{
					textEncoded=true;
				}
				if (line.IndexOf("Content-Type: text/plain")==0)
				{
					hasPlainText=true;
				}
				if (line.IndexOf("Content-Type: text/html")==0)
				{
					hasHtmlText=true;
				}
				if (line.IndexOf("X-Mailer: DotNetOpenMail " + VersionInfo.GetInstance().ToString())==0)
				{
					//hasDefaultXMailerHeader=true;
				}
				if (line.IndexOf("X-MyHeader1: my header number one") == 0)
				{
					//hasCustomHeader1=true;
				}
				if (line.IndexOf("X-MyHeader2: my header number two") == 0)
				{
					//hasCustomHeader2=true;
				}

				// log.Debug("Line +ACIAKw-i+-": +ACIAKw-line);				
			}
			Assert.IsTrue(toHeaderEncoded, "To Header not encoded");
			Assert.IsTrue(fromHeaderEncoded, "From Header not encoded");
			Assert.IsTrue(subjectHeaderEncoded, "Subject Header not encoded");
			//Assert.IsTrue(hasSubjectHeader, "Missing Subject Header");
			//Assert.IsTrue(hasMimeVersion, "Missing Mime Version header");
			//Assert.IsTrue(hasMultipartAlternative, "Missing Mime Multipart/Alternative setting");
			Assert.IsTrue(hasPlainText, "Missing Plain Text");
			Assert.IsTrue(hasHtmlText, "Missing HTML");
			Assert.IsTrue(htmlEncoded, "HTML Not encoded");
			Assert.IsTrue(textEncoded, "Text Not encoded");
			//Assert.IsTrue(hasDefaultXMailerHeader, "Missing X-Mailer Header");
			//Assert.IsTrue(hasCustomHeader1, "Missing Custom Header 1");
			//Assert.IsTrue(hasCustomHeader2, "Missing Custom Header 2");
			//Assert.AreEqual(2, quotedPrintableParts, "Expected 2 quoted printable declarations, found +ACIAKw-quotedPrintableParts);
		
			


		}
		public void TestHtmlAndText() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test HTML and Text";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			emailmessage.AddCustomHeader("X-MyHeader1", "my header number one");
			emailmessage.AddCustomHeader("X-MyHeader2", "my header number two");

			emailmessage.Send(_smtpserver);

			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			log.Debug(content);

			int i=0;
			String line=null;
			bool hasToHeader=false;
			bool hasFromHeader=false;
			bool hasSubjectHeader=false;
			bool hasMimeVersion=false;
			bool hasMultipartAlternative=false;
			bool hasPlainText=false;
			bool hasHtmlText=false;
			bool hasDefaultXMailerHeader=false;
			bool hasCustomHeader1=false;
			bool hasCustomHeader2=false;
			int quotedPrintableParts=0;

			String expectedToAddress=TestAddressHelper.GetToAddress().Name+" <"+TestAddressHelper.GetToAddress().Email+">";
			
			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				if (line.IndexOf("To: "+expectedToAddress)==0) 
				{
					hasToHeader=true;
				}
				if (line.IndexOf("From: "+emailmessage.FromAddress.ToString())==0) 
				{
					hasFromHeader=true;
				}
				if (line.IndexOf("Subject: "+emailmessage.Subject)==0) 
				{
					hasSubjectHeader=true;
				}
				if (line.IndexOf("MIME-Version: 1.0")==0) 
				{
					hasMimeVersion=true;
				}
				if (line.IndexOf("Content-Type: multipart/alternative;")==0) 
				{
					hasMultipartAlternative=true;
				}
				if (line.IndexOf("Content-Type: text/html")==0) 
				{
					hasHtmlText=true;
				}
				if (line.IndexOf("Content-Type: text/plain")==0) 
				{
					hasPlainText=true;
				}
				if (line.IndexOf("Content-Transfer-Encoding: quoted-printable")==0) 
				{
					quotedPrintableParts++;
				}
				if (line.IndexOf("X-Mailer: DotNetOpenMail") == 0)
				{
					hasDefaultXMailerHeader=true;
				}
				if (line.IndexOf("X-MyHeader1: my header number one") == 0)
				{
					hasCustomHeader1=true;
				}
				if (line.IndexOf("X-MyHeader2: my header number two") == 0)
				{
					hasCustomHeader2=true;
				}

				// log.Debug("Line "+i+": "+line);				
			}
			Assert.IsTrue(hasToHeader, "Missing TO Header");
			Assert.IsTrue(hasFromHeader, "Missing FROM Header");
			Assert.IsTrue(hasSubjectHeader, "Missing Subject Header");
			Assert.IsTrue(hasMimeVersion, "Missing Mime Version header");
			Assert.IsTrue(hasMultipartAlternative, "Missing Mime Multipart/Alternative setting");
			Assert.IsTrue(hasPlainText, "Missing Plain Text");
			Assert.IsTrue(hasHtmlText, "Missing HTML");
			Assert.IsTrue(hasDefaultXMailerHeader, "Missing X-Mailer Header");
			Assert.IsTrue(hasCustomHeader1, "Missing Custom Header 1");
			Assert.IsTrue(hasCustomHeader2, "Missing Custom Header 2");
			Assert.AreEqual(2, quotedPrintableParts, "Expected 2 quoted printable declarations, found "+quotedPrintableParts);
		
			
		

		}
		public void TestExtraHeader() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddCcAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddBccAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="Extra Header";
			emailmessage.HeaderEncoding=DotNetOpenMail.Encoding.EncodingType.QuotedPrintable;
			emailmessage.XMailer="NUnit Test Mailer";
			emailmessage.AddCustomHeader("MyHeader", "Value");
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			String content=emailmessage.ToDataString();
			emailmessage.Send(_smtpserver);

		}
		public void TestDocFile()
		{
			EmailMessage mail = new EmailMessage();

			FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\TestWord.doc");		
			Assert.IsTrue(fileinfo.Exists);

			FileAttachment fileAttachment = new FileAttachment(fileinfo);
			fileAttachment.ContentType = "application/msword";
			
			//EmailAddress emailAddress = new EmailAddress(emailAddressParam); 
			mail.TextPart=new TextAttachment("Here is your file");
			mail.AddMixedAttachment(fileAttachment);

			mail.FromAddress=TestAddressHelper.GetFromAddress();
			mail.AddToAddress("*****@*****.**");	

			SmtpServer smtpServer = TestAddressHelper.GetSmtpServer();

			mail.Send(smtpServer);
		}
Esempio n. 18
0
        /// <summary>
        ///     SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="scene">Can be null</param>
        public void SendEmail(UUID objectID, string address, string subject, string body, IScene scene)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            const string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                              + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                              + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                              + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                              + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            if (scene != null)
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition,
                                              out LastObjectRegionName, scene);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    try
                    {
                        //Creation EmailMessage

                        string fromEmailAddress;

                        if (scene != null && objectID != UUID.Zero)
                            fromEmailAddress = objectID.ToString() + "@" + m_HostName;
                        else
                            fromEmailAddress = "no-reply@" + m_HostName;

                        EmailMessage emailMessage = new EmailMessage
                                                        {
                                                            FromAddress =
                                                                new EmailAddress(fromEmailAddress),
                                                            Subject = subject
                                                        };

                        //To - Only One
                        emailMessage.AddToAddress(new EmailAddress(address));
                        //Text
                        emailMessage.BodyText = body;
                        if (scene != null)
                        {
                            // If Object Null Dont Include Object Info Headers (Offline IMs)
                            if(objectID != UUID.Zero)
                                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                        "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                        LastObjectPosition + "\n\n";

                            emailMessage.BodyText += emailMessage.BodyText;
                        }

                        //Config SMTP Server
                        //Set SMTP SERVER config
                        SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                        // Add authentication only when requested
                        if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                            smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                        //Add timeout of 15 seconds
                        smtpServer.ServerTimeout = 15000;
                        //Send Email Message
                        didError = !emailMessage.Send(smtpServer);

                        //Log
                        if (!didError)
                            MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " +
                                                      fromEmailAddress);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                        didError = true;
                    }
                }
                if (((didError) || (m_localOnly)) && (scene != null))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName, scene);
                    if (part != null)
                    {
                        IScenePresence sp = scene.GetScenePresence(part.OwnerID);
                        if ((sp != null) && (!sp.IsChildAgent))
                        {
                            sp.ControllingClient.SendAlertMessage(
                                "llEmail: email module not configured for outgoing emails");
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@", StringComparison.Ordinal));
                UUID toID = new UUID(guid);

                if (IsLocal(toID, scene))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                                          {
                                              time =
                                                  ((int)
                                                   ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds))
                                                  .
                                                  ToString(CultureInfo.InvariantCulture),
                                              subject = subject,
                                              sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                              message = "Object-Name: " + LastObjectName +
                                                        "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                        LastObjectPosition + "\n\n" + body,
                                              toPrimID = toID
                                          });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                                      {
                                          time =
                                              ((int)
                                               ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                                              ToString(CultureInfo.InvariantCulture),
                                          subject = subject,
                                          sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                          message = body,
                                          toPrimID = toID
                                      };
                    IEmailConnector conn = Framework.Utilities.DataManager.RequestPlugin<IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            try
            {
                //Creation EmailMessage
                EmailMessage emailMessage = new EmailMessage();
                //From
                emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                //To - Only One
                emailMessage.AddToAddress(new EmailAddress(address));
                //Subject
                emailMessage.Subject = subject;
                //TEXT Body
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                            "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                            LastObjectPosition + "\n\n" + body;

                int len = emailMessage.BodyText.Length;
                if ((address.Length + subject.Length + len) > 4096)
                {
                    len -= address.Length;
                    len -= subject.Length;
                    emailMessage.BodyText = emailMessage.BodyText.Substring(0, len);
                }

                //Config SMTP Server
                //Set SMTP SERVER config
                SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                // Add authentication only when requested
                //
                if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                {
                    //Authentication
                    smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                }
                //Send Email Message
                emailMessage.Send(smtpServer);

                //Log
                m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
            }
            catch (Exception e)
            {
                m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                m_log.Error("[EMAIL] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                if (!m_localOnly)
                {
                    string m_ObjectRegionName;
                    SceneObjectPart part = findPrim(objectID, out m_ObjectRegionName);
                    if (part != null)
                    {
                        lock (m_Scenes)
                        {
                            foreach (Scene s in m_Scenes.Values)
                            {
                                ScenePresence SP = s.GetScenePresence(part.OwnerID);
                                if (SP != null)
                                {
                                    if (!SP.IsChildAgent)
                                        SP.ControllingClient.SendAlertMessage("llEmail: email module not configured for outgoing emails");
                                }
                            }
                        }
                    }
                }
                // regular email, send it out
                try
                {
                    //Creation EmailMessage
                    EmailMessage emailMessage = new EmailMessage();
                    //From
                    emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                    //To - Only One
                    emailMessage.AddToAddress(new EmailAddress(address));
                    //Subject
                    emailMessage.Subject = subject;
                    //TEXT Body
                    resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                    emailMessage.BodyText = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                    //Config SMTP Server
                    //Set SMTP SERVER config
                    SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                    // Add authentication only when requested
                    //
                    if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                    {
                        //Authentication
                        smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                    }
                    //Send Email Message
                    emailMessage.Send(smtpServer);

                    //Log
                    m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
                }
                catch (Exception e)
                {
                    m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                }
            }
            else
            {
                // inter object email, keep it in the family
                Email email = new Email();
                email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
                email.subject = subject;
                email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
                email.message = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID))
                {
                    // object in this region
                    InsertEmail(toID, email);
                }
                else
                {
                    // object on another region

                    //This should be dealt with by other modules, not us
                }
            }

            //DONE: Message as Second Life style
            //20 second delay - AntiSpam System - for now only 10 seconds
            DelayInSeconds(10);
        }
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;
            string[] host = address.Split('@');
            string hostcheck = host[1];
            WebClient client = new WebClient();
            value = client.DownloadString("http://osxchange.org/router.php?grid=" + hostcheck);
            // string routeraddress = address.en
            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[OpenSimEmail] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                m_log.Error("[OpenSimEmail] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
            if (value != "false" && !address.EndsWith(m_InterObjectHostname))
            {
                m_log.Info(value);
                Hashtable ReqHash = new Hashtable();
                ReqHash["fromaddress"] = objectID.ToString() + "@" + m_HostName;
                ReqHash["toaddress"] = address.ToString();
                ReqHash["timestamp"] = ConvertToUnixTimestamp(DateTime.UtcNow);
                ReqHash["subject"] = subject.ToString();
                ReqHash["objectname"] = LastObjectName;
                ReqHash["position"] = LastObjectPosition;
                ReqHash["region"] = LastObjectRegionName;
                ReqHash["messagebody"] = body.ToString();

                Hashtable result = GenericXMLRPCRequestRemote(ReqHash,
                        "send_email");
                m_log.Error("Address not match intern mail" + address);
                if (!Convert.ToBoolean(result["success"]))
                {
                    return;
                }
                DelayInSeconds(20);

            }




            else if (!address.EndsWith(m_InterObjectHostname))
            {
                // regular email, send it out

                //Creation EmailMessage
                EmailMessage emailMessage = new EmailMessage();
                //From
                emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                //To - Only One
                emailMessage.AddToAddress(new EmailAddress(address));
                //Subject
                emailMessage.Subject = subject;
                //TEXT Body
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                          "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                          LastObjectPosition + "\n\n" + body;

                //Config SMTP Server
                //Set SMTP SERVER config
                SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                // Add authentication only when requested
                //
                if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                {
                    //Authentication
                    smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                }
                //Send Email Message
                emailMessage.Send(smtpServer);

                //Log
                m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);


            }
            else if (address.EndsWith(m_InterObjectHostname))
            {
                Hashtable ReqHash = new Hashtable();
                ReqHash["fromaddress"] = objectID.ToString() + "@" + m_HostName;
                ReqHash["toaddress"] = address.ToString();
                ReqHash["timestamp"] = ConvertToUnixTimestamp(DateTime.UtcNow);
                ReqHash["subject"] = subject.ToString();
                ReqHash["objectname"] = LastObjectName;
                ReqHash["position"] = LastObjectPosition;
                ReqHash["region"] = LastObjectRegionName;
                ReqHash["messagebody"] = body.ToString();
                m_log.Error("Address is internal" + address);
                Hashtable result = GenericXMLRPCRequest(ReqHash,
                        "send_email");

                if (!Convert.ToBoolean(result["success"]))
                {
                    return;
                }
                DelayInSeconds(20);
            }
        }
		public void TestFileFromString() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="Here's your license";
	
			emailmessage.TextPart=new TextAttachment("This is a license.\r\n\r\n"+
				"We will spend your money on a new plasma TV.");
		
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+
				"<p>This is a license.</p>\r\n"+
				"<p>We will spend your money on a new <i>plasma TV</i>.</p>\r\n"+
				"</body></html>");
		
			String content="This is String Line 1\r\nThis is String Line 2";

			FileAttachment fileAttachment=new FileAttachment(content);
			
			//fileAttachment.ContentType
			fileAttachment.FileName="License.txt";
			fileAttachment.CharSet=System.Text.Encoding.ASCII;
			fileAttachment.ContentType="text/plain";
			fileAttachment.Encoding=DotNetOpenMail.Encoding.EncodingType.SevenBit;
			emailmessage.AddMixedAttachment(fileAttachment);
			
			//emailmessage.Send(TestAddressHelper.GetSmtpServer());		
		}
		public void TestFor7BitHeader() 
		{
			EmailMessage emailmessage=new EmailMessage();
			emailmessage.HeaderCharSet=System.Text.ASCIIEncoding.ASCII;
			emailmessage.HeaderEncoding=DotNetOpenMail.Encoding.EncodingType.SevenBit;

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test HTML and Text";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.TextPart.CharSet=System.Text.ASCIIEncoding.ASCII;
			emailmessage.TextPart.Encoding=DotNetOpenMail.Encoding.EncodingType.SevenBit;

			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");
			emailmessage.HtmlPart.CharSet=System.Text.ASCIIEncoding.ASCII;
			emailmessage.HtmlPart.Encoding=DotNetOpenMail.Encoding.EncodingType.SevenBit;

			//emailmessage.Send(_smtpserver);

			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			//log.Debug(content);

			int i=0;
			String line=null;

			String expectedToAddress=TestAddressHelper.GetToAddress().Name+" <"+TestAddressHelper.GetToAddress().Email+">";
			int has7Bit=0;
			int hasUSASCII=0;

			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				if (line.IndexOf("Content-Transfer-Encoding: 7bit")==0) 
				{
					has7Bit++;
				}
				if (line.IndexOf("charset=\"us-ascii\"")>0) 
				{
					hasUSASCII++;
				}
				//log.Debug("Line "+i+": "+line);				
			}
			Assert.AreEqual(2, has7Bit, "Not enough 7bit lines");
			Assert.AreEqual(2, hasUSASCII, "Not enough us-ascii lines");

		}
		public void TestLargerBinaryFileFromStream() 
		{

			String filename="casingTheJoint.jpg";

			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="Here's your file";
	
			emailmessage.TextPart=new TextAttachment("This a zip file.");
		
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>"+
				"<p>This a zip file.</p>\r\n");

			FileInfo fileinfo=new FileInfo(@"..\..\TestFiles\"+filename);		
			FileStream filestream = fileinfo.OpenRead();

			MemoryStream stream=new MemoryStream();

			StreamWriter sw=new StreamWriter(stream);

			sw.Flush();

			//BinaryReader br=new BinaryReader(stream);

			BinaryReader br=new BinaryReader(filestream);
			byte[] bytes=br.ReadBytes((int) fileinfo.Length);
			br.Close();

			FileAttachment fileAttachment=new FileAttachment(bytes);
			
			//fileAttachment.ContentType
			fileAttachment.FileName=filename;
			fileAttachment.ContentType="application/zip";
			emailmessage.AddMixedAttachment(fileAttachment);
			
			emailmessage.Send(TestAddressHelper.GetSmtpServer());		
		}
		private EmailMessage GetBasicMessage() 
		{
			EmailMessage emailmessage=new EmailMessage();
	
			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
	
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());	
	
			emailmessage.Subject="PDF Test";
	
			emailmessage.TextPart=new TextAttachment("This a PDF File");
		
			emailmessage.HtmlPart=new HtmlAttachment("<p>This is a PDF File</p>\r\n");

			return emailmessage;

		}
		public void TestRelatedAttachments() 
		{

			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="EmailMessageTests Test Related Graphic";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br><img src=\"cid:mycontentid\">\r\n<strong>HTML</strong><br>\r\npart.</body></html>");
			FileInfo relatedfileinfo=new FileInfo(@"..\..\TestFiles\grover.jpg");
			Assert.IsTrue(relatedfileinfo.Exists);
			FileAttachment relatedfileattachment=new FileAttachment(relatedfileinfo,"mycontentid");
			relatedfileattachment.ContentType="image/jpeg";			
			emailmessage.AddRelatedAttachment(relatedfileattachment);
			//emailmessage.Send(_smtpserver);
			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			
			int i=0;
			String line=null;
			bool hasMimeVersion=false;
			bool hasMixedHeader=false;
			bool relatedHeaderComesFirst=false;
			bool hasMultipartAlternative=false;
			bool hasPlainText=false;
			bool hasHtmlText=false;
			bool hasAttachment=false;
			bool hasRelatedHeader=false;
			int quotedPrintableParts=0;

			String expectedToAddress=TestAddressHelper.GetToAddress().Name+" <"+TestAddressHelper.GetToAddress().Email+">";
			//log.Debug("To Address is "+expectedToAddress);
			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				if (line.IndexOf("Content-Type: multipart/mixed")==0) 
				{
					hasMixedHeader=true;

				}

				if (line.IndexOf("MIME-Version: 1.0")==0) 
				{
					hasMimeVersion=true;
				}
				if (line.IndexOf("Content-Type: multipart/alternative;")==0) 
				{
					hasMultipartAlternative=true;
				}
				if (line.IndexOf("Content-Type: text/html")==0) 
				{
					hasHtmlText=true;
				}
				if (line.IndexOf("Content-Type: text/plain")==0) 
				{
					hasPlainText=true;
				}
				if (line.IndexOf("Content-Type: image/jpeg")==0) 
				{
					hasAttachment=true;
				}
				if (line.IndexOf("Content-Transfer-Encoding: quoted-printable")==0) 
				{
					quotedPrintableParts++;
				}
				if (line.IndexOf("/9j/4AAQSkZJRgABAQEASABIAAD/")==0) 
				{
					hasAttachment=true;
				}
				if (line.IndexOf("Content-Type: multipart/related")>=0)
				{
					hasRelatedHeader=true;
					if (!hasMultipartAlternative && !hasMixedHeader) 
					{
						relatedHeaderComesFirst=true;
					}
				}
				//log.Debug("Line "+i+": "+line);				
			}
			Assert.IsFalse(hasMixedHeader, "Should not have a  multipart/mixed header");
			Assert.IsTrue(hasMimeVersion, "Missing Mime Version header");
			Assert.IsTrue(relatedHeaderComesFirst, "The related header should come first");
			Assert.IsTrue(hasMultipartAlternative, "Missing Mime Multipart/Alternative setting");
			Assert.IsTrue(hasPlainText, "Missing Plain Text");
			Assert.IsTrue(hasHtmlText, "Missing HTML");
			Assert.IsTrue(hasAttachment, "Missing the base64 Attachment");
			Assert.IsTrue(hasRelatedHeader, "Missing the related header.");
			Assert.AreEqual(2, quotedPrintableParts, "Expected 2 quoted printable declarations, found "+quotedPrintableParts);


		}
Esempio n. 27
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                m_log.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                // regular email, send it out
                try
                {
                    //Creation EmailMessage
                    EmailMessage emailMessage = new EmailMessage();
                    //From
                    emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                    //To - Only One
                    emailMessage.AddToAddress(new EmailAddress(address));
                    //Subject
                    emailMessage.Subject = subject;
                    //TEXT Body
                    resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                    emailMessage.BodyText = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                    //Config SMTP Server
                    //Set SMTP SERVER config
                    SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                    // Add authentication only when requested
                    //
                    if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                    {
                        //Authentication
                        smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                    }
                    //Send Email Message
                    emailMessage.Send(smtpServer);

                    //Log
                    m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
                }
                catch (Exception e)
                {
                    m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                }
            }
            else
            {
                // inter object email, keep it in the family
                Email email = new Email();
                email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
                email.subject = subject;
                email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
                email.message = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID)) // TODO FIX check to see if it is local
                {
                    // object in this region
                    InsertEmail(toID, email);
                }
                else
                {
                    // object on another region
                    // TODO FIX
                }
            }
        }
		public void TestHeaders() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddCcAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddCcAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddBccAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddBccAddress(TestAddressHelper.GetToAddress());		
			emailmessage.Subject="Test Headers";
			emailmessage.XMailer="NUnit Test Mailer";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			String content=emailmessage.ToDataString();
			StringReader sr=new StringReader(content);
			
			int i=0;
			String line=null;
			bool hasToHeader=false;
			bool hasFromHeader=false;
			bool hasSubjectHeader=false;
			bool hasBccHeader=false;
			bool hasCcHeader=false;
			bool hasXMailerHeader=false;

			String expectedToAddress=TestAddressHelper.GetToAddress().Name+" <"+TestAddressHelper.GetToAddress().Email+">";


			while ((line=sr.ReadLine())!=null) 
			{
				i++;
				if (line.IndexOf("To: "+expectedToAddress+", "+expectedToAddress)==0) 
				{
					hasToHeader=true;
				}
				if (line.IndexOf("Cc: "+expectedToAddress+", "+expectedToAddress)==0) 
				{
					hasCcHeader=true;
				}
				if (line.IndexOf("Bcc: "+expectedToAddress+", "+expectedToAddress)==0) 
				{
					hasBccHeader=true;
				}

				if (line.IndexOf("From: "+emailmessage.FromAddress.ToString())==0) 
				{
					hasFromHeader=true;
				}
				if (line.IndexOf("Subject: "+emailmessage.Subject)==0) 
				{
					hasSubjectHeader=true;
				}
				if (line.IndexOf("X-Mailer: NUnit Test Mailer")==0) 
				{
					hasXMailerHeader=true;
				}
				
			}
			Assert.IsTrue(hasToHeader, "Missing TO Header");
			Assert.IsTrue(hasFromHeader, "Missing FROM Header");
			Assert.IsTrue(hasSubjectHeader, "Missing Subject Header");
			Assert.IsTrue(hasCcHeader, "Missing Cc Header");
			Assert.IsFalse(hasBccHeader, "Bcc Header Shouldn't appear");
			Assert.IsTrue(hasXMailerHeader, "Missing XMailer Header");
			//emailmessage.Send(_smtpserver);

		}
Esempio n. 29
0
        /// <summary>
        ///   SendMail function utilized by llEMail
        /// </summary>
        /// <param name = "objectID"></param>
        /// <param name = "address"></param>
        /// <param name = "subject"></param>
        /// <param name = "body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                        + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                        + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    try
                    {
                        //Creation EmailMessage
                        EmailMessage emailMessage = new EmailMessage
                                                        {
                                                            FromAddress =
                                                                new EmailAddress(objectID.ToString() + "@" + m_HostName)
                                                        };
                        //From
                        //To - Only One
                        emailMessage.AddToAddress(new EmailAddress(address));
                        //Subject
                        emailMessage.Subject = subject;
                        //Text
                        emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                LastObjectPosition + "\n\n" + body;

                        //Config SMTP Server
                        //Set SMTP SERVER config
                        SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                        // Add authentication only when requested
                        if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                            smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                        //Add timeout of 15 seconds
                        smtpServer.ServerTimeout = 15000;
                        //Send Email Message
                        didError = !emailMessage.Send(smtpServer);

                        //Log
                        if (!didError)
                            MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() +
                                       "@" + m_HostName);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                        didError = true;
                    }
                }
                if ((didError) || (m_localOnly))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName);
                    if (part != null)
                    {
                        lock (m_Scenes)
                        {
#if (!ISWIN)
                            foreach (IScene s in m_Scenes.Values)
                            {
                                IScenePresence SP = s.GetScenePresence(part.OwnerID);
                                if ((SP != null) && (!SP.IsChildAgent))
                                {
                                    SP.ControllingClient.SendAlertMessage("llEmail: email module not configured for outgoing emails");
                                }
                            }
#else
                            foreach (IScenePresence SP in m_Scenes.Values.Select(s => s.GetScenePresence(part.OwnerID)).Where(SP => (SP != null) && (!SP.IsChildAgent)))
                            {
                                SP.ControllingClient.SendAlertMessage(
                                    "llEmail: email module not configured for outgoing emails");
                            }
#endif
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                                  {
                                      time =
                                          ((int) ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                                          ToString(),
                                      subject = subject,
                                      sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                      message = "Object-Name: " + LastObjectName +
                                                "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                LastObjectPosition + "\n\n" + body,
                                      toPrimID = toID
                                  });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                    {
                        time =
                            ((int)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                            ToString(),
                        subject = subject,
                        sender = objectID.ToString() + "@" + m_InterObjectHostname,
                        message = body,
                        toPrimID = toID
                    };
                    Aurora.Framework.IEmailConnector conn = Aurora.DataManager.DataManager.RequestPlugin<Aurora.Framework.IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
		public void TestLongSubjectEncoded() 
		{
			EmailMessage emailmessage=new EmailMessage();

			emailmessage.FromAddress=TestAddressHelper.GetFromAddress();
			emailmessage.AddToAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddCcAddress(TestAddressHelper.GetToAddress());
			emailmessage.AddBccAddress(TestAddressHelper.GetToAddress());
			emailmessage.Subject="Join our Group's Fundraising Efforts é test test test Gulf Little League";
			emailmessage.HeaderEncoding=DotNetOpenMail.Encoding.EncodingType.QuotedPrintable;
			emailmessage.XMailer="NUnit Test Mailer";
			emailmessage.TextPart=new TextAttachment("This\r\nis the\r\ntext\r\npart.");
			emailmessage.HtmlPart=new HtmlAttachment("<html><body>This<br>\r\nis the<br>\r\n<strong>HTML</strong><br>\r\npart.</body></html>");

			String content=emailmessage.ToDataString();
			emailmessage.Send(_smtpserver);

		}