Example #1
0
        public static bool Send(string from, string to, string subject, string content, string smtpServerAddress, string smtpAccount, string smtpPassword)
        {
            EmailMessage emailMessage = new EmailMessage();

            emailMessage.FromAddress = new EmailAddress(from);
            emailMessage.AddToAddress(new EmailAddress(to));
            emailMessage.Subject  = subject;
            emailMessage.HtmlPart = new HtmlAttachment(content);

            emailMessage.HeaderCharSet    = System.Text.Encoding.GetEncoding("GB2312");
            emailMessage.HeaderEncoding   = EncodingType.Base64;
            emailMessage.HtmlPart.CharSet = System.Text.Encoding.GetEncoding("gb2312");

            SmtpServer smtpServer = new SmtpServer(smtpServerAddress);

            smtpServer.SmtpAuthToken = new SmtpAuthToken(smtpAccount, smtpPassword);
            smtpServer.ServerTimeout = 3000;
            emailMessage.ContentType = "TEXT/HTML";
            try
            {
                emailMessage.Send(smtpServer);
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #2
0
        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());
        }
Example #3
0
        public void email()
        {
            try
            {
                EmailMessage emailMessage = new EmailMessage();

                emailMessage.FromAddress = new EmailAddress("*****@*****.**",
                                                            "Charles Swann");

                emailMessage.AddToAddress(new EmailAddress("*****@*****.**",
                                                           "hari"));

                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>");

                emailMessage.Send(new SmtpServer("localhost"));
            }
            catch (Exception ex)
            {
            }
        }
Example #4
0
        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);
        }
Example #5
0
        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());
        }
Example #6
0
        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;
            }
        }
Example #7
0
        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());
        }
Example #8
0
        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
        }
Example #9
0
        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);
        }
Example #10
0
        private EmailMessage BuildEmailMessage(string subject, string content, string from, string to)
        {
            EmailMessage emailMessage = new EmailMessage();

            emailMessage.FromAddress = new EmailAddress(from);
            emailMessage.AddToAddress(new EmailAddress(to));
            emailMessage.Subject          = subject;
            emailMessage.HtmlPart         = new HtmlAttachment(content);
            emailMessage.HeaderCharSet    = messageEncoding;
            emailMessage.HeaderEncoding   = EncodingType.Base64;
            emailMessage.HtmlPart.CharSet = messageEncoding;
            emailMessage.ContentType      = messagetype;

            return(emailMessage);
        }
        public void TestFor8BitHeader()
        {
            EmailMessage emailmessage = new EmailMessage();

            emailmessage.HeaderCharSet  = System.Text.ASCIIEncoding.ASCII;
            emailmessage.HeaderEncoding = DotNetOpenMail.Encoding.EncodingType.EightBit;

            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.EightBit;

            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.EightBit;

            //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    has8Bit           = 0;
            int    hasUSASCII        = 0;

            while ((line = sr.ReadLine()) != null)
            {
                i++;
                if (line.IndexOf("Content-Transfer-Encoding: 8bit") == 0)
                {
                    has8Bit++;
                }
                if (line.IndexOf("charset=\"us-ascii\"") > 0)
                {
                    hasUSASCII++;
                }
                log.Debug("Line " + i + ": " + line);
            }
            Assert.AreEqual(2, has8Bit, "Not enough 8bit lines");
            Assert.AreEqual(2, hasUSASCII, "Not enough us-ascii lines");
        }
Example #12
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());
        }
        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);
        }
Example #14
0
        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);
        }
Example #15
0
        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);
        }
Example #16
0
        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);
        }
Example #17
0
        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());
        }
Example #18
0
        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());
        }
Example #19
0
        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");
        }
Example #20
0
        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);
        }
        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);
        }
Example #22
0
        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);
        }
Example #23
0
        private int m_MaxEmailSize           = 4096; // largest email allowed by default, as per lsl docs.

        #region IEmailModule Members

        /// <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 = "@" + m_HostName;
                        if (scene != null)
                        {
                            fromEmailAddress = objectID.ToString() + "@" + m_HostName;
                        }
                        else
                        {
                            fromEmailAddress = "noreply@" + 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)
                        {
                            emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                    "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                    LastObjectPosition + "\n\n" + 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);
                }
            }
        }
Example #24
0
        public override ReturnValue GetMailContent(int orderId, int releaseID, TProgram_Email mi)
        {
            ReturnValue _result = new ReturnValue();

            System.Globalization.NumberFormatInfo nfi = Utilities.CurrentNumberFormat;


            #region getOrderInfo and Check

            TOrderNu _tOrder = new TOrderNu();
            _result = _tOrder.getOrderById(orderId);
            if (_result.Success == false)
            {
                return(_result);
            }

            _tOrder = _result.Object as TOrderNu;


            if (_tOrder.OrderId == 0)
            {
                _result.Success    = false;
                _result.ErrMessage = "the order doesn't exits";

                return(_result);
            }

            TOrderNu _emailAddress = new TOrderNu();
            _result = _emailAddress.getMailAddress(_tOrder.CustomerId);
            if (_result.Success == false)
            {
                return(_result);
            }

            _emailAddress = _result.Object as TOrderNu;



            TOrder_Line_ItemNu _tOrdersDetail = new TOrder_Line_ItemNu();
            _result = _tOrdersDetail.getOrdersDetail(orderId);
            if (_result.Success == false)
            {
                return(_result);
            }

            EntityList _orderDetails = _result.ObjectList;


            if (_orderDetails.Count == 0)
            {
                _result.Success    = false;
                _result.ErrMessage = "the order doesn't exits";

                return(_result);
            }


            #endregion

            try
            {
                #region setup EmailMessage

                EmailMessage _mail = new EmailMessage();

                if (_emailAddress.MailBCC.IndexOf(";") > 0)
                {
                    _emailAddress.MailBCC = _emailAddress.MailBCC.Remove(_emailAddress.MailBCC.Length - 1, 1);
                }

                if (_emailAddress.MailCC.IndexOf(";") > 0)
                {
                    _emailAddress.MailCC = _emailAddress.MailCC.Remove(_emailAddress.MailCC.Length - 1, 1);
                }

                if (_emailAddress.MailTo.IndexOf(";") > 0)
                {
                    _emailAddress.MailTo = _emailAddress.MailTo.Remove(_emailAddress.MailTo.Length - 1, 1);
                }

                mi.BccAddress = _emailAddress.MailBCC;
                mi.CCAddress  = _emailAddress.MailCC;



                #region Order Summary
                string MailContent = mi.FullText
                                     .Replace("&Firstname", _tOrder.FirstName)
                                     .Replace("&zorderid", _tOrder.OrderId.ToString())
                                     .Replace("&OrderDate", _tOrder.OrderDate.ToString("MM/dd/yyyy"))
                                     .Replace("&ztotalproductamount", _tOrder.TotalProductAmount.ToString("C", nfi))
                                     .Replace("&zTotalShipping", (_tOrder.TotalShipping).ToString("C", nfi))
                                     .Replace("&zTotalTax", _tOrder.TotalTax.ToString("C", nfi))
                                     .Replace("&zTotalOrderAmount", _tOrder.TotalOrderAmount.ToString("C", nfi))
                                     .Replace("&ShippingMethod", _tOrder.ShipMethod)
                                     .Replace("&ShippedDate", _tOrder.ShippedDate.Value.ToString("MM/dd/yyyy"));

                #endregion

                #region Order Detail
                string RepeatTemp = "";

                if (MailContent.IndexOf("&orderinfo") > 0)
                {
                    RepeatTemp = " <table width =\"100%\" cellpadding=\"1\"><tr><td >Item No</td><td>Description</td><td >Unit Price</td><td>Quantity</td></tr>";

                    foreach (TOrder_Line_ItemNu drItem in _orderDetails)
                    {
                        RepeatTemp = RepeatTemp + "<tr><td >" + drItem.PartNumber + "</td><td>" + drItem.ProductName
                                     + "</td><td >" + drItem.Price.ToString("C") + "</td><td>" + drItem.Quantity.ToString() + "</td></tr>";
                    }
                    RepeatTemp = RepeatTemp + "</TABLE>";
                }

                MailContent = MailContent.Replace("&orderinfo", RepeatTemp);
                #endregion

                #region Shipping Detail

                RepeatTemp = "";

                if (MailContent.IndexOf("&shipmentnfo") > 0)
                {
                    RepeatTemp = " <table  width =\"100%\" cellpadding=\"1\">";

                    int _packageNumber = 1;

                    TOrder_Line_Shipment_Carton _tOrder_Line_Shipment_Carton = new TOrder_Line_Shipment_Carton();
                    _result = _tOrder_Line_Shipment_Carton.getOrderLineShipmentCartonByOrderID(orderId, releaseID);
                    if (_result.Success == false)
                    {
                        return(_result);
                    }

                    EntityList cartonList = _result.ObjectList;



                    TOrder_Line_Shipment_ASN _tOrder_Line_Shipment_ASN = new TOrder_Line_Shipment_ASN();
                    _result = _tOrder_Line_Shipment_ASN.getOrderLineShipmentASNByOrderID(orderId, releaseID);
                    if (_result.Success == false)
                    {
                        return(_result);
                    }

                    EntityList asnList = _result.ObjectList;



                    foreach (TOrder_Line_Shipment_Carton _carton in cartonList)
                    {
                        if (asnList.Count != 0)
                        {
                            if (string.IsNullOrEmpty(_carton.PACKAGE_TRACE_ID) == false)
                            {
                                RepeatTemp = RepeatTemp + "<tr><td >Package " + _packageNumber.ToString() + "  Tracking Number:" + _carton.PACKAGE_TRACE_ID + "  " +
                                             "(<a href=\"{0}\">TrackOrder</a>)" + "</td></tr>";
                            }
                            else
                            {
                                RepeatTemp = RepeatTemp + "<tr><td >Package " + _packageNumber.ToString() + "  Tracking Number:N/A</td></tr>";
                            }

                            RepeatTemp = RepeatTemp + "<tr><td ><br /> <table width =\"100%\" cellpadding=\"1\"><tr><td > Item No</td>" +
                                         "<td>Description</td><td>Qty in Package</td></tr>";
                            foreach (TOrder_Line_Shipment_ASN _asn in asnList)
                            {
                                TOrder_Line_ItemNu _orderDetail = this.getOrderLine(_orderDetails, _asn);
                                RepeatTemp = RepeatTemp + " <tr><td >" + _orderDetail.PartNumber + "</td><td>" + _orderDetail.ProductName +
                                             "</td><td>" + Convert.ToInt16(Convert.ToDouble(_asn.PIECES_TO_MOVE)).ToString() + "</td></tr>";
                                RepeatTemp = RepeatTemp.Replace("{0}", _orderDetail.TrackingURL + _carton.PACKAGE_TRACE_ID);
                            }

                            RepeatTemp = RepeatTemp + "</table><br /></td></tr>";

                            _packageNumber++;
                        }
                    }


                    RepeatTemp = RepeatTemp + "</TABLE>";
                }

                MailContent = MailContent.Replace("&shipmentnfo", RepeatTemp);

                #endregion


                _mail.HtmlPart = new HtmlAttachment(MailContent);



                _mail.FromAddress = new EmailAddress(mi.RespondTo);
                _mail.Subject     = mi.Subject;

                if (Common.IsTest == true)
                {
                    string[] maillist = Common.TestMailTo.Split(';');
                    foreach (string _item in maillist)
                    {
                        _mail.AddToAddress(new EmailAddress(_item));
                    }

                    _result.Table = Common.TestMailTo;
                }
                else
                {
                    if (string.IsNullOrEmpty(_emailAddress.MailTo) == true)
                    {
                        _result.Success    = false;
                        _result.ErrMessage = "Email To Address is empty";
                        return(_result);
                    }
                    else
                    {
                        string[] bcclist = _emailAddress.MailTo.Split(';');
                        foreach (string _item in bcclist)
                        {
                            _mail.AddToAddress(new EmailAddress(_item));
                        }
                    }

                    _result.Table = _emailAddress.MailTo;
                }


                if (string.IsNullOrEmpty(mi.BccAddress) == false)
                {
                    string[] bcclist = mi.BccAddress.Split(';');
                    foreach (string _item in bcclist)
                    {
                        _mail.AddBccAddress(new EmailAddress(_item));
                    }
                }
                if (string.IsNullOrEmpty(mi.CCAddress) == false)
                {
                    string[] bcclist = mi.CCAddress.Split(';');
                    foreach (string _item in bcclist)
                    {
                        _mail.AddCcAddress(new EmailAddress(_item));
                    }
                }


                _result.ObjectValue = _mail;

                #endregion
            }
            catch (Exception ex)
            {
                _result.Success    = false;
                _result.ErrMessage = ex.ToString();
            }

            return(_result);
        }
Example #25
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
                }
            }
        }
Example #26
0
        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);
        }
Example #27
0
        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);
        }
        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 (!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);
            }
        }
Example #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)
            {
                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))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // 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
                        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)
                        {
                            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);
                        didError = true;
                    }
                }
                if ((didError) || (m_localOnly))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName);
                    if (part != null)
                    {
                        lock (m_Scenes)
                        {
                            foreach (Scene 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
            {
                // 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 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);
        }