Exemple #1
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);
        }
Exemple #2
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);
        }
Exemple #3
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);
        }
Exemple #4
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);
        }
Exemple #5
0
        /// <summary>
        /// This method uses DotNetOpenMail. DotNetOpenMail doesn't work in Medium Trust.
        /// For Medium Trust use the SendMailNormal method.
        /// If Web.config setting RunningInMediumTrust is true then this method delegates to SendMailNormal.
        /// </summary>
        /// <param name="smtpSettings"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="cc"></param>
        /// <param name="bcc"></param>
        /// <param name="subject"></param>
        /// <param name="messageBody"></param>
        /// <param name="html"></param>
        /// <param name="priority"></param>
        public static void SendEmail(
            SmtpSettings smtpSettings,
            string from,
            string to,
            string cc,
            string bcc,
            string subject,
            string messageBody,
            bool html,
            string priority)
        {
            if ((ConfigurationManager.AppSettings["DisableSmtp"] != null) && (ConfigurationManager.AppSettings["DisableSmtp"] == "true"))
            {
                log.Info("Not Sending email because DisableSmtp is true in config.");
                return;
            }

            if ((smtpSettings == null) || (!smtpSettings.IsValid))
            {
                log.Error("Invalid smtp settings detected in SendEmail ");
                return;
            }

            // DotNetOpenMail doesn't work in Medium Trust so fall back to built in System.Net classes
            if (ConfigurationManager.AppSettings["RunningInMediumTrust"] != null)
            {
                string runningInMediumTrust = ConfigurationManager.AppSettings["RunningInMediumTrust"];
                if (string.Equals(runningInMediumTrust, "true", StringComparison.InvariantCultureIgnoreCase))
                {
                    SendEmailNormal(smtpSettings, from, to, cc, bcc, subject, messageBody, html, priority);
                    return;
                }
            }

            if (ConfigurationManager.AppSettings["DisableDotNetOpenMail"] != null)
            {
                string disable = ConfigurationManager.AppSettings["DisableDotNetOpenMail"];
                if (string.Equals(disable, "true", StringComparison.InvariantCultureIgnoreCase))
                {
                    SendEmailNormal(smtpSettings, from, to, cc, bcc, subject, messageBody, html, priority);
                    return;
                }
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("In SendEmail({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})",
                                from,
                                to,
                                cc,
                                bcc,
                                subject,
                                messageBody,
                                html,
                                priority);
            }

            EmailMessage mail        = new EmailMessage();
            EmailAddress fromAddress = new EmailAddress(from);

            mail.FromAddress = fromAddress;

            if (smtpSettings.PreferredEncoding.Length > 0)
            {
                mail.HeaderEncoding = DotNetOpenMail.Encoding.EncodingType.Base64;
                mail.HeaderCharSet  = Encoding.GetEncoding(smtpSettings.PreferredEncoding);
            }

            if (html)
            {
                mail.HtmlPart = new HtmlAttachment(messageBody);

                if (smtpSettings.PreferredEncoding.Length > 0)
                {
                    mail.HtmlPart.Encoding = DotNetOpenMail.Encoding.EncodingType.Base64;
                    mail.HtmlPart.CharSet  = Encoding.GetEncoding(smtpSettings.PreferredEncoding);
                }
            }
            else
            {
                mail.TextPart = new TextAttachment(messageBody);
                if (smtpSettings.PreferredEncoding.Length > 0)
                {
                    mail.TextPart.Encoding = DotNetOpenMail.Encoding.EncodingType.Base64;
                    mail.TextPart.CharSet  = Encoding.GetEncoding(smtpSettings.PreferredEncoding);
                }
            }

            EmailAddress toAddress;

            if (to.Contains(";"))
            {
                string[] toAddresses = to.Split(new char[] { ';' });
                foreach (string address in toAddresses)
                {
                    if (Email.IsValidEmailAddressSyntax(address))
                    {
                        toAddress = new EmailAddress(address);

                        mail.ToAddresses.Add(toAddress);
                    }
                }
            }
            else
            {
                if (Email.IsValidEmailAddressSyntax(to))
                {
                    toAddress = new EmailAddress(to);
                    mail.ToAddresses.Add(toAddress);
                }
            }

            if (mail.ToAddresses.Count == 0)
            {
                throw new MailException("no valid email address provided for To");
            }

            if (cc.Length > 0)
            {
                EmailAddress ccAddress = new EmailAddress(cc);
                mail.CcAddresses.Add(ccAddress);
            }
            if (bcc.Length > 0)
            {
                EmailAddress bccAddress = new EmailAddress(bcc);
                mail.BccAddresses.Add(bccAddress);
            }
            mail.Subject = subject.RemoveLineBreaks();

            switch (priority)
            {
            //X-Priority Values:
            // 1 (Highest), 2 (High), 3 (Normal), 4 (Low), 5 (Lowest)
            case PriorityHigh:
                mail.AddCustomHeader("X-Priority", "1");
                mail.AddCustomHeader("X-MSMail-Priority", "High");
                break;

            case PriorityLow:
                mail.AddCustomHeader("X-Priority", "5");
                mail.AddCustomHeader("X-MSMail-Priority", "Low");
                break;

            case PriorityNormal:
            default:
                mail.AddCustomHeader("X-Priority", "3");
                mail.AddCustomHeader("X-MSMail-Priority", "Normal");
                break;
            }

            int timeoutMilliseconds = ConfigHelper.GetIntProperty("SMTPTimeoutInMilliseconds", 15000);

            SmtpServer smtpServer = new SmtpServer(smtpSettings.Server, smtpSettings.Port, smtpSettings.UseSsl);

            smtpServer.ServerTimeout = timeoutMilliseconds;

            if (smtpSettings.RequiresAuthentication)
            {
                smtpServer.SmtpAuthToken
                    = new SmtpAuthToken(
                          smtpSettings.User,
                          smtpSettings.Password);
            }

            try
            {
                mail.Send(smtpServer);
            }
            catch (MailException ex)
            {
                log.Error("error sending email to " + to + " from " + from + ", message was: " + messageBody, ex);
            }
            catch (SocketException ex)
            {
                log.Error("error sending email to " + to + " from " + from + ", message was: " + messageBody, ex);
            }
        }