Exemplo n.º 1
0
        static void AssertParse(string text, string encoded, InternetAddressList expected)
        {
            var buffer = Encoding.UTF8.GetBytes(text);
            InternetAddressList result = null;

            try {
                result = InternetAddressList.Parse(text);
            } catch {
                Assert.Fail("Parse(string): {0}", text);
            }
            AssertInternetAddressListsEqual(encoded, expected, result);

            try {
                result = InternetAddressList.Parse(buffer);
            } catch {
                Assert.Fail("Parse(byte[]): {0}", text);
            }
            AssertInternetAddressListsEqual(encoded, expected, result);

            try {
                result = InternetAddressList.Parse(buffer, 0);
            } catch {
                Assert.Fail("Parse(byte[], int): {0}", text);
            }
            AssertInternetAddressListsEqual(encoded, expected, result);

            try {
                result = InternetAddressList.Parse(buffer, 0, buffer.Length);
            } catch {
                Assert.Fail("Parse(byte[], int, int): {0}", text);
            }
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
        private async void RunProcess(object state)
        {
            var cancellationToken = (CancellationToken)state;
            var ordersToSend      = (await _dataReaderReceiveActor
                                     .Ask <List <object> >(new RecordsReaderMessage(_readFilePath, typeof(Order))
            {
                Skip = _skipCounter, Take = _maxMailsAtOnce
            }, cancellationToken))
                                    .Cast <Order>();

            foreach (var order in ordersToSend)
            {
                var message = await _messageConverterReceiveActor
                              .Ask <MimeMessage>(order);

                Console.WriteLine(await _messageSenderReceiveActor
                                  .Ask(new SendEmailMessage(message,
                                                            InternetAddress.Parse(_from),
                                                            InternetAddressList.Parse(order.Email),
                                                            _host,
                                                            _port,
                                                            _from,
                                                            _password)));
            }
            await _dataWriterReceiveActor
            .Ask(new RecordsWriterMessage(_writeFilePath, ordersToSend.ToList()));
        }
        public void TestMailboxesWithRfc2047EncodedNames()
        {
            var expected = new InternetAddressList();
            var mailbox  = new MailboxAddress("", "");
            InternetAddressList result;
            string text;

            expected.Add(mailbox);

            mailbox.Name    = "Kristoffer Brånemyr";
            mailbox.Address = "*****@*****.**";
            text            = "=?iso-8859-1?q?Kristoffer_Br=E5nemyr?= <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "François Pons";
            mailbox.Address = "*****@*****.**";
            text            = "=?iso-8859-1?q?Fran=E7ois?= Pons <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
        public void TestSimpleAddrSpec()
        {
            var expected = new InternetAddressList();
            var mailbox  = new MailboxAddress("", "");
            InternetAddressList result;
            string text;

            expected.Add(mailbox);

            text            = "*****@*****.**";
            mailbox.Address = "*****@*****.**";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            text            = "fejj";
            mailbox.Address = "fejj";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
Exemplo n.º 5
0
        internal IEnumerable <MimeMessage> GetEmails(EmailAccount emailAccount)
        {
            var emailAddress  = EmailAddress.Parse(emailAccount.Username ?? emailAccount.Email);
            var domainManager = FindAndEnsureDomainAvailable(emailAddress.Domain);
            var account       = TryOrNull(() => domainManager.Accounts.ItemByAddress[emailAddress.ToString()]);

            if (account == null)
            {
                yield break;
            }

            for (int i = 0; i < account.Messages.Count; i++)
            {
                var    message           = account.Messages[i];
                var    mimeMessage       = new MimeMessage();
                string adjustedToAddress = message.To.Replace(">,", ">");
                mimeMessage.To.AddRange(InternetAddressList.Parse(adjustedToAddress));
                mimeMessage.From.Add(InternetAddress.Parse($"\"{message.From}\" <{message.FromAddress}>"));
                mimeMessage.Subject = message.Subject;
                var bodyBuilder = new BodyBuilder {
                    HtmlBody = message.HTMLBody, TextBody = message.Body
                };
                mimeMessage.Body = bodyBuilder.ToMessageBody();
                yield return(mimeMessage);
            }
        }
        private async void RunProcess(object state)
        {
            var cancellationToken = (CancellationToken)state;
            var ordersToSend      = (await _queryBus.Send <ReadCsv, ICollection>(new ReadCsv(typeof(Order),
                                                                                             _readFilePath)
            {
                Skip = _skipCounter, Take = _maxMailsAtOnce
            }, cancellationToken)).Cast <Order>().ToList();

            _skipCounter += _maxMailsAtOnce;
            var ordersSended = new List <Order>();

            foreach (var order in ordersToSend)
            {
                var message = await _queryBus.Send <ConvertOrderToMessage, MimeMessage>(new ConvertOrderToMessage(order), cancellationToken);

                var recepient = order?.Email;
                await _commandBus.Send(new SendMail(message, InternetAddress.Parse(_from),
                                                    InternetAddressList.Parse(recepient), _host, _port, _from, _password), cancellationToken);

                ordersSended.Add(order);
            }

            await _commandBus.Send(new SaveToCsv(_writeFilePath, ordersSended), cancellationToken);
        }
        private MimeMessage CreateMailMessage(MailMessage notification)
        {
            var message = new MimeMessage {
                Subject = notification.Subject
            };
            var builder = new BodyBuilder();

            if (!String.IsNullOrEmpty(notification.To))
            {
                message.To.AddRange(InternetAddressList.Parse(notification.To));
            }

            if (!String.IsNullOrEmpty(notification.From))
            {
                message.From.AddRange(InternetAddressList.Parse(notification.From));
            }
            else
            {
                message.From.AddRange(InternetAddressList.Parse(Settings.Current.SmtpFrom));
            }

            if (!String.IsNullOrEmpty(notification.Body))
            {
                builder.HtmlBody = notification.Body;
            }

            message.Body = builder.ToMessageBody();
            return(message);
        }
Exemplo n.º 8
0
        public async Task Send(string from, string fromEmail, string toEmail, string subject, string body, SmtpSettings smtpSettings, CancellationToken cancellationToken = default)
        {
            var msg = new MimeMessage(InternetAddressList.Parse($"{from} <{fromEmail}>"), InternetAddressList.Parse(toEmail), subject, new TextPart("html")
            {
                Text = body
            });

            using var client = new SmtpClient();
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.ConnectAsync))) {
                await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, smtpSettings.SecureSocketOptions, cancellationToken);

                depTrack.Success();
            }
            if (!string.IsNullOrWhiteSpace(smtpSettings.User))
            {
                using var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.AuthenticateAsync));
                await client.AuthenticateAsync(smtpSettings.User, smtpSettings.Password, cancellationToken);

                depTrack.Success();
            }
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.SendAsync))) {
                await client.SendAsync(msg, cancellationToken);

                depTrack.Success();
            }
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.DisconnectAsync))) {
                await client.DisconnectAsync(true, cancellationToken);

                depTrack.Success();
            }
        }
Exemplo n.º 9
0
        private async Task SendMail(AlarmOrEvent alarm, MailNotification no, SmtpSettings settings)
        {
            try {
                string source = alarm.IsSystem ? "System" : alarm.ModuleName;

                var msg = new StringBuilder();
                msg.AppendLine($"Severity: {alarm.Severity}");
                msg.AppendLine($"Message:  {alarm.Message}");
                msg.AppendLine($"Source:   {source}");
                msg.AppendLine($"Time UTC: {alarm.Time}");
                msg.AppendLine($"Time:     {alarm.Time.ToDateTime().ToLocalTime()}");
                if (!string.IsNullOrEmpty(alarm.Details))
                {
                    msg.AppendLine($"Details:  {alarm.Details}");
                }

                string subject = no.Subject
                                 .Replace("{severity}", alarm.Severity.ToString())
                                 .Replace("{message}", alarm.Message)
                                 .Replace("{source}", source);

                var messageToSend = new MimeMessage(
                    from: new InternetAddress[] { InternetAddress.Parse(settings.From) },
                    to: InternetAddressList.Parse(no.To),
                    subject: subject,
                    body: new TextPart(MimeKit.Text.TextFormat.Plain)
                {
                    Text = msg.ToString()
                }
                    );

                using (var smtp = new MailKit.Net.Smtp.SmtpClient()) {
                    smtp.MessageSent += (sender, args) => { /* args.Response */ };
                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    await smtp.ConnectAsync(settings.Server, settings.Port, (SecureSocketOptions)settings.SslOptions);

                    if (!string.IsNullOrEmpty(settings.AuthUser) || !string.IsNullOrEmpty(settings.AuthPass))
                    {
                        await smtp.AuthenticateAsync(settings.AuthUser, settings.AuthPass);
                    }
                    await smtp.SendAsync(messageToSend);

                    await smtp.DisconnectAsync(quit : true);

                    Console.Out.WriteLine($"Sent notification mail (to: {no.To}, subject: {subject})");
                }
            }
            catch (Exception exp) {
                Console.Error.WriteLine("Failed to send notification mail: " + exp.Message);
            }
        }
Exemplo n.º 10
0
        public void TestExampleMailboxWithCommentsFromRfc5322()
        {
            var expected = new InternetAddressList();
            InternetAddressList result;
            string text;

            text = "Pete(A nice \\) chap) <pete(his account)@silly.test(his host)>";
            expected.Add(new MailboxAddress("Pete", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
Exemplo n.º 11
0
        public void TestObsoleteMailboxRoutingSyntaxWithEmptyDomains()
        {
            const string        text     = "Routed Address <@route1,,@route2,,,@route3:[email protected]>";
            const string        encoded  = "Routed Address <@route1,@route2,@route3:[email protected]>";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new MailboxAddress("Routed Address", new [] { "route1", "route2", "route3" }, "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 12
0
        public void TestMailboxWith8bitName()
        {
            const string        encoded  = "Patrik =?iso-8859-1?b?RqVkbHRzdHKldm0=?= <*****@*****.**>";
            const string        text     = "Patrik F¥dltstr¥vm <*****@*****.**>";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new MailboxAddress("Patrik F¥dltstr¥vm", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 13
0
        public void TestMailboxWithDotsInTheName()
        {
            const string        encoded  = "\"Nathaniel S. Borenstein\" <*****@*****.**>";
            const string        text     = "Nathaniel S. Borenstein <*****@*****.**>";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new MailboxAddress("Nathaniel S. Borenstein", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 14
0
        public void TestObsoleteMailboxRoutingSyntax()
        {
            var expected = new InternetAddressList();
            InternetAddressList result;
            string text;

            text = "Routed Address <@route:[email protected]>";

            expected.Add(new MailboxAddress("Routed Address", new [] { "route" }, "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
Exemplo n.º 15
0
        public void TestMailboxWith8bitName()
        {
            var expected = new InternetAddressList();
            InternetAddressList result;
            string text;

            text = "Patrik F¥dltstr¥vm <*****@*****.**>";

            expected.Add(new MailboxAddress("Patrik F¥dltstr¥vm", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
Exemplo n.º 16
0
        public void TestExampleAddrSpecWithQuotedLocalPartAndCommentsFromRfc822()
        {
            const string        text     = "\":sysmail\"@  Some-Group. Some-Org,\n Muhammed.(I am  the greatest) Ali @(the)Vegas.WBA";
            const string        encoded  = "\":sysmail\"@Some-Group.Some-Org, [email protected]";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new MailboxAddress("", "\":sysmail\"@Some-Group.Some-Org"));
            expected.Add(new MailboxAddress("", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 17
0
        public void TestExampleGroupWithCommentsFromRfc5322()
        {
            const string        text     = "A Group(Some people):Chris Jones <c@(Chris's host.)public.example>, [email protected], John <*****@*****.**> (my dear friend); (the end of the group)";
            const string        encoded  = "A Group: Chris Jones <*****@*****.**>, [email protected], John <*****@*****.**>;";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new GroupAddress("A Group", new InternetAddress[] {
                new MailboxAddress("Chris Jones", "*****@*****.**"),
                new MailboxAddress("", "*****@*****.**"),
                new MailboxAddress("John", "*****@*****.**")
            }));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 18
0
        public void TestListWithGroupAndAddrspec()
        {
            const string        text     = "GNOME Hackers: Miguel de Icaza <*****@*****.**>, Havoc Pennington <*****@*****.**>;, [email protected]";
            string              encoded  = "GNOME Hackers: Miguel de Icaza <*****@*****.**>, Havoc Pennington\n\t<*****@*****.**>;, [email protected]";
            var                 expected = new InternetAddressList();
            InternetAddressList result;

            expected.Add(new GroupAddress("GNOME Hackers", new InternetAddress[] {
                new MailboxAddress("Miguel de Icaza", "*****@*****.**"),
                new MailboxAddress("Havoc Pennington", "*****@*****.**")
            }));
            expected.Add(new MailboxAddress("", "*****@*****.**"));

            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(encoded, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(encoded, expected, result);
        }
Exemplo n.º 19
0
        static void AssertParseFails(string text)
        {
            var buffer = Encoding.UTF8.GetBytes(text);

            try {
                InternetAddressList.Parse(text);
                Assert.Fail("InternetAddressList.Parse() should fail to parse \"{0}\".", text);
            } catch (ParseException) {
                // success
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }

            try {
                InternetAddressList.Parse(buffer);
                Assert.Fail("InternetAddressList.Parse() should fail to parse \"{0}\".", text);
            } catch (ParseException) {
                // success
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }

            try {
                InternetAddressList.Parse(buffer, 0);
                Assert.Fail("InternetAddressList.Parse() should fail to parse \"{0}\".", text);
            } catch (ParseException) {
                // success
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }

            try {
                InternetAddressList.Parse(buffer, 0, buffer.Length);
                Assert.Fail("InternetAddressList.Parse() should fail to parse \"{0}\".", text);
            } catch (ParseException) {
                // success
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }
        }
Exemplo n.º 20
0
        public void TestParseWhiteSpace()
        {
            try {
                InternetAddress.Parse("   ");
                Assert.Fail("InternetAddress.Parse() should fail to parse whitespace.");
            } catch (ParseException ex) {
                Assert.AreEqual(3, ex.TokenIndex, "ParseException did not have the correct token index.");
                Assert.AreEqual(3, ex.ErrorIndex, "ParseException did not have the error index.");
            } catch {
                Assert.Fail("InternetAddress.Parse() should throw ParseException.");
            }

            try {
                InternetAddressList.Parse("   ");
                Assert.Fail("InternetAddressList.Parse() should fail to parse whitespace.");
            } catch (ParseException ex) {
                Assert.AreEqual(3, ex.TokenIndex, "ParseException did not have the correct token index.");
                Assert.AreEqual(3, ex.ErrorIndex, "ParseException did not have the error index.");
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }
        }
Exemplo n.º 21
0
        /// <inheritdoc />
        public override string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null)
        {
            // validate smtp server
            if (smtpInfo == null || string.IsNullOrEmpty(smtpInfo.Server))
            {
                if (string.IsNullOrWhiteSpace(Host.SMTPServer))
                {
                    return("SMTP Server not configured");
                }

                smtpInfo = new SmtpInfo
                {
                    Server         = Host.SMTPServer,
                    Authentication = Host.SMTPAuthentication,
                    Username       = Host.SMTPUsername,
                    Password       = Host.SMTPPassword,
                    EnableSSL      = Host.EnableSMTPSSL,
                };
            }

            var mailMessage = new MimeMessage();

            mailMessage.From.Add(ParseAddressWithDisplayName(displayName: mailInfo.FromName, address: mailInfo.From));
            if (!string.IsNullOrEmpty(mailInfo.Sender))
            {
                mailMessage.Sender = MailboxAddress.Parse(mailInfo.Sender);
            }

            // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
            if (!string.IsNullOrEmpty(mailInfo.To))
            {
                mailInfo.To = mailInfo.To.Replace(";", ",");
                mailMessage.To.AddRange(InternetAddressList.Parse(mailInfo.To));
            }

            if (!string.IsNullOrEmpty(mailInfo.CC))
            {
                mailInfo.CC = mailInfo.CC.Replace(";", ",");
                mailMessage.Cc.AddRange(InternetAddressList.Parse(mailInfo.CC));
            }

            if (!string.IsNullOrEmpty(mailInfo.BCC))
            {
                mailInfo.BCC = mailInfo.BCC.Replace(";", ",");
                mailMessage.Bcc.AddRange(InternetAddressList.Parse(mailInfo.BCC));
            }

            if (!string.IsNullOrEmpty(mailInfo.ReplyTo))
            {
                mailInfo.ReplyTo = mailInfo.ReplyTo.Replace(";", ",");
                mailMessage.ReplyTo.AddRange(InternetAddressList.Parse(mailInfo.ReplyTo));
            }

            mailMessage.Priority = (MessagePriority)mailInfo.Priority;

            // Only modify senderAddress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpInfo.Authentication == "1" || smtpInfo.Authentication == "2")
            {
                // if the senderAddress is the email address of the Host then switch it smtpUsername if different
                // if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailInfo.Sender;
                    var senderDisplayName = mailInfo.FromName;
                    var needUpdateSender  = false;
                    if (smtpInfo.Username.Contains("@") && senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpInfo.Username, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpInfo.Username;
                        needUpdateSender = true;
                    }

                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }

                    if (needUpdateSender)
                    {
                        mailMessage.Sender = ParseAddressWithDisplayName(displayName: senderDisplayName, address: senderAddress);
                    }
                }
                else if (smtpInfo.Username.Contains("@"))
                {
                    mailMessage.Sender = ParseAddressWithDisplayName(
                        displayName: Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle,
                        address: smtpInfo.Username);
                }
            }

            var builder = new BodyBuilder
            {
                TextBody = Mail.ConvertToText(mailInfo.Body),
            };

            if (mailInfo.BodyFormat == MailFormat.Html)
            {
                builder.HtmlBody = mailInfo.Body;
            }

            // attachments
            if (mailInfo.Attachments != null)
            {
                foreach (var attachment in mailInfo.Attachments.Where(attachment => attachment.Content != null))
                {
                    builder.Attachments.Add(attachment.Filename, attachment.Content, ContentType.Parse(attachment.ContentType));
                }
            }

            // message
            mailMessage.Subject = HtmlUtils.StripWhiteSpace(mailInfo.Subject, true);
            mailMessage.Body    = builder.ToMessageBody();

            smtpInfo.Server = smtpInfo.Server.Trim();

            if (!SmtpServerRegex.IsMatch(smtpInfo.Server))
            {
                return(Localize.GetString("SMTPConfigurationProblem"));
            }

            try
            {
                var smtpHostParts = smtpInfo.Server.Split(':');
                var host          = smtpHostParts[0];
                var port          = 25;

                if (smtpHostParts.Length > 1)
                {
                    // port is guaranteed to be of max 5 digits numeric by the RegEx check
                    port = int.Parse(smtpHostParts[1]);
                    if (port < 1 || port > 65535)
                    {
                        return(Localize.GetString("SmtpInvalidPort"));
                    }
                }

                // to workaround problem in 4.0 need to specify host name
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect(host, port, SecureSocketOptions.Auto);

                    switch (smtpInfo.Authentication)
                    {
                    case "":
                    case "0":     // anonymous
                        break;

                    case "1":     // basic
                        if (!string.IsNullOrEmpty(smtpInfo.Username) &&
                            !string.IsNullOrEmpty(smtpInfo.Password))
                        {
                            smtpClient.Authenticate(smtpInfo.Username, smtpInfo.Password);
                        }

                        break;

                    case "2":     // NTLM (Not Supported by MailKit)
                        throw new NotSupportedException("NTLM authentication is not supported by MailKit provider");
                    }

                    smtpClient.Send(mailMessage);
                    smtpClient.Disconnect(true);
                }

                return(string.Empty);
            }
            catch (Exception exc)
            {
                var retValue = Localize.GetString("SMTPConfigurationProblem") + " ";

                // mail configuration problem
                if (exc.InnerException != null)
                {
                    retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                    Exceptions.Exceptions.LogException(exc.InnerException);
                }
                else
                {
                    retValue += exc.Message;
                    Exceptions.Exceptions.LogException(exc);
                }

                return(retValue);
            }
        }
Exemplo n.º 22
0
 internal MailMessageBuilder WithToAddress(string email)
 {
     _inner.To.AddRange(InternetAddressList.Parse(email));
     return(this);
 }
Exemplo n.º 23
0
        public void TestSorting()
        {
            var messages = new List <MessageSummary> ();
            IList <MessageSummary> sorted;
            MessageSummary         summary;

            summary                  = new MessageSummary(0);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "aaaa";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 520;
            messages.Add(summary);

            summary                  = new MessageSummary(1);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "bbbb";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 265;
            messages.Add(summary);

            summary                  = new MessageSummary(2);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "cccc";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 520;
            messages.Add(summary);

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Arrival });
            Assert.AreEqual(0, sorted[0].Index, "Sorting by arrival failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by arrival failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by arrival failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseArrival });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by reverse arrival failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by reverse arrival failed.");
            Assert.AreEqual(0, sorted[2].Index, "Sorting by reverse arrival failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Subject });
            Assert.AreEqual(0, sorted[0].Index, "Sorting by subject failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by subject failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseSubject });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by reverse subject failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by reverse subject failed.");
            Assert.AreEqual(0, sorted[2].Index, "Sorting by reverse subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Size });
            Assert.AreEqual(1, sorted[0].Index, "Sorting by size failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Size, OrderBy.Subject });
            Assert.AreEqual(1, sorted[0].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(0, sorted[1].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by size+subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseSize, OrderBy.ReverseSubject });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(0, sorted[1].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(1, sorted[2].Index, "Sorting by size+subject failed.");
        }
Exemplo n.º 24
0
        private static MimeMessage CreateMailMessage(MailInfo mailInfo, SmtpInfo smtpInfo)
        {
            var mailMessage = new MimeMessage();

            mailMessage.From.Add(ParseAddressWithDisplayName(displayName: mailInfo.FromName, address: mailInfo.From));
            if (!string.IsNullOrEmpty(mailInfo.Sender))
            {
                mailMessage.Sender = MailboxAddress.Parse(mailInfo.Sender);
            }

            // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
            if (!string.IsNullOrEmpty(mailInfo.To))
            {
                mailInfo.To = mailInfo.To.Replace(";", ",");
                mailMessage.To.AddRange(InternetAddressList.Parse(mailInfo.To));
            }

            if (!string.IsNullOrEmpty(mailInfo.CC))
            {
                mailInfo.CC = mailInfo.CC.Replace(";", ",");
                mailMessage.Cc.AddRange(InternetAddressList.Parse(mailInfo.CC));
            }

            if (!string.IsNullOrEmpty(mailInfo.BCC))
            {
                mailInfo.BCC = mailInfo.BCC.Replace(";", ",");
                mailMessage.Bcc.AddRange(InternetAddressList.Parse(mailInfo.BCC));
            }

            if (!string.IsNullOrEmpty(mailInfo.ReplyTo))
            {
                mailInfo.ReplyTo = mailInfo.ReplyTo.Replace(";", ",");
                mailMessage.ReplyTo.AddRange(InternetAddressList.Parse(mailInfo.ReplyTo));
            }

            mailMessage.Priority = ToMessagePriority(mailInfo.Priority);

            // Only modify senderAddress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpInfo.Authentication == "1" || smtpInfo.Authentication == "2")
            {
                // if the senderAddress is the email address of the Host then switch it smtpUsername if different
                // if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailInfo.Sender;
                    var senderDisplayName = mailInfo.FromName;
                    var needUpdateSender  = false;
                    if (smtpInfo.Username.Contains("@") &&
                        senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpInfo.Username, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpInfo.Username;
                        needUpdateSender = true;
                    }

                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }

                    if (needUpdateSender)
                    {
                        mailMessage.Sender = ParseAddressWithDisplayName(
                            displayName: senderDisplayName,
                            address: senderAddress);
                    }
                }
                else if (smtpInfo.Username.Contains("@"))
                {
                    mailMessage.Sender = ParseAddressWithDisplayName(
                        displayName: Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle,
                        address: smtpInfo.Username);
                }
            }

            var builder = new BodyBuilder {
                TextBody = Mail.ConvertToText(mailInfo.Body),
            };

            if (mailInfo.BodyFormat == MailFormat.Html)
            {
                builder.HtmlBody = mailInfo.Body;
            }

            // attachments
            if (mailInfo.Attachments != null)
            {
                foreach (var attachment in mailInfo.Attachments.Where(attachment => attachment.Content != null))
                {
                    builder.Attachments.Add(attachment.Filename, attachment.Content, ContentType.Parse(attachment.ContentType));
                }
            }

            // message
            mailMessage.Subject = HtmlUtils.StripWhiteSpace(mailInfo.Subject, true);
            mailMessage.Body    = builder.ToMessageBody();
            return(mailMessage);
        }
Exemplo n.º 25
0
        public void TestSimpleMailboxes()
        {
            var expected = new InternetAddressList();
            var mailbox  = new MailboxAddress("", "");
            InternetAddressList result;
            string text;

            expected.Add(mailbox);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "this is a folded name";
            mailbox.Address = "*****@*****.**";
            text            = "this is\n\ta folded name <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey fejj Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey \"fejj\" Stedfast <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey \"fejj\" Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "\"Jeffrey \\\"fejj\\\" Stedfast\" <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Stedfast, Jeffrey";
            mailbox.Address = "*****@*****.**";
            text            = "\"Stedfast, Jeffrey\" <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "[email protected] (Jeffrey Stedfast)";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <fejj(recursive (comment) block)@helixcode.(and a comment here)com>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <[email protected].>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }