Exemplo n.º 1
10
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress(_settings.Value.Author, _settings.Value.Email));
            emailMessage.To.Add(new MailboxAddress("", email));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("html") {Text = message};
            try
            {
                var client = new SmtpClient();
                //     {
                // client.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                // client.Authenticate(_settings.Value.Email, _settings.Value.Password);
                //  client.Send(emailMessage);
                // client.Disconnect(true);
                await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                await client.AuthenticateAsync(_settings.Value.Email, _settings.Value.Password);

                await client.SendAsync(emailMessage);
                await client.DisconnectAsync(true);
                //  }
            }
            catch (Exception ex) //todo add another try to send email
            {
                var e = ex;
                throw;
            }
           
        }
Exemplo n.º 2
1
        private async Task SendAsync(MimeMessage mailMessage)
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.PortResetPassword, true);

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password);

                    await client.SendAsync(mailMessage);
                }
                catch
                {
                    //log an error message or throw an exception, or both.
                    throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);

                    client.Dispose();
                }
            }
        }
Exemplo n.º 3
0
        public async Task SendAsync(IdentityMessage message)
        {
            // настройка логина, пароля отправителя
            var from = "*****@*****.**";
            var pass = "******";

            // создаем письмо: message.Destination - адрес получателя
            var emailMessage = new MimeMessage()
            {
                Subject = message.Subject,
                Body    = new TextPart(MimeKit.Text.TextFormat.Html)
                {
                    Text = message.Body
                }
            };

            emailMessage.From.Add(new MailboxAddress("Администрация сайта", from));
            emailMessage.To.Add(new MailboxAddress("", message.Destination));

            // адрес и порт smtp-сервера, с которого мы и будем отправлять письмо
            using (var client = new SmtpClient())
            {
                await client.ConnectAsync("smtp.gmail.com", 465);

                await client.AuthenticateAsync(from, pass);

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }
        }
Exemplo n.º 4
0
        private async Task SendAsync(MimeMessage mailMessage)
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    //client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.Auto);

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // Note: only needed if the SMTP server requires authentication
                    await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password);

                    await client.SendAsync(mailMessage);
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);

                    client.Dispose();
                }
            }
        }
Exemplo n.º 5
0
        public async Task <bool> SendAsync(string subject, string message, string senderEmail, string receiverEmail)
        {
            using (SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(_emailConfiguration.Host, _emailConfiguration.Port);

                await client.AuthenticateAsync(_emailConfiguration.Username, _emailConfiguration.Password);

                MimeMessage mailMessage = new MimeMessage
                {
                    Body = new TextPart(MimeKit.Text.TextFormat.Html)
                    {
                        Text = message
                    },
                    From =
                    {
                        new MailboxAddress(_emailConfiguration.DisplayName, senderEmail)
                    },
                    To =
                    {
                        new MailboxAddress(receiverEmail)
                    },
                    Subject = subject
                };

                await client.SendAsync(mailMessage);

                await client.DisconnectAsync(true);
            }

            return(true);
        }
        public async Task <SimplyHandlerResult> Handle(EmailSendDto input, CancellationToken cancellationToken)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress(_emailSenderConfiguration.TitleName,
                                                     _emailSenderConfiguration.Email));
            emailMessage.To.Add(new MailboxAddress(_emailSenderConfiguration.TitleName, input.SendeeEmail));
            emailMessage.Subject = input.Subject;
            emailMessage.Body    = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = input.Text
            };

            await _smtpClient.ConnectAsync(
                _emailSenderConfiguration.Host, _emailSenderConfiguration.Port,
                _emailSenderConfiguration.UseSSL, cancellationToken);

            await _smtpClient.AuthenticateAsync(_emailSenderConfiguration.Email, _emailSenderConfiguration.Password,
                                                cancellationToken);

            await _smtpClient.SendAsync(emailMessage, cancellationToken);

            await _smtpClient.DisconnectAsync(true, cancellationToken);

            return(new SimplyHandlerResult(true));
        }
Exemplo n.º 7
0
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress("Mohamad Ravaei", "*****@*****.**"));

                mimeMessage.To.Add(new MailboxAddress(email));

                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = message
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    await client.ConnectAsync("mail.ravasa.ir", 25, false);

                    await client.AuthenticateAsync("*****@*****.**", "Mmgrdd211!");

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
Exemplo n.º 8
0
        static async void SendMailAsync(string FromAddress, string Password, string Contain, string Title, string ToAddress)
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MimeKit.MailboxAddress(FromAddress, FromAddress));
            message.To.Add(new MimeKit.MailboxAddress(ToAddress, ToAddress));
            message.Subject = Title;
            var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain);

            textPart.Text = @Contain;
            message.Body  = textPart;
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    await client.ConnectAsync("smtp.gmail.com", 587);

                    await client.AuthenticateAsync(FromAddress, Password);

                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    Form2 form2 = new Form2();
                    form2.text(ex.ToString());

                    form2.ShowDialog();
                }
            }
        }
Exemplo n.º 9
0
        private async Task SendAsync(MimeMessage mailMessage)
        {
            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, true);

                    //client.AuthenticationMechanisms.Remove("XOAUTH2");
                    await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password);

                    await client.SendAsync(mailMessage);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);

                    client.Dispose();
                }
            }
        }
Exemplo n.º 10
0
        private async Task <int> SendAsync(MimeMessage mailMessage)
        {
            int Result = 0;

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.None);

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password);

                    await client.SendAsync(mailMessage);

                    Result = 1;
                }
                catch (Exception ex)
                {
                    ErrMsg = ex.Message;
                    Result = -1;
                    //log an error message or throw an exception, or both.
                    //throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);

                    client.Dispose();
                }
            }
            return(Result);
        }
Exemplo n.º 11
0
        public async Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.SenderEmail));
            mimeMessage.To.Add(MailboxAddress.Parse(email));
            mimeMessage.Subject = subject;

            var builder = new BodyBuilder {
                HtmlBody = htmlMessage
            };

            mimeMessage.Body = builder.ToMessageBody();
            try
            {
                using var client = new MailKit.Net.Smtp.SmtpClient();
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, _emailSettings.UseSsl).ConfigureAwait(false);

                await client.AuthenticateAsync(_emailSettings.SenderEmail, _emailSettings.Password);

                await client.SendAsync(mimeMessage).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
        public async Task <IActionResult> SendEmail(EmailInfo emailInfo)
        {
            var currentMonth = DateTime.Now.Date.ToString("MMMM", new CultureInfo("uk-UA"));

            var date      = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, DateTime.Now.Day);
            var nextMonth = date.ToString("MMMM", new CultureInfo("uk-UA"));

            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Admin", "*****@*****.**"));
            emailMessage.To.Add(new MailboxAddress("Students", "*****@*****.**"));
            emailMessage.Subject = "Проїзні на " + nextMonth;
            emailMessage.Body    = new TextPart("html")
            {
                Text = "Доброго дня!" + "<br>" + "Роздача проїзних на " + nextMonth + ": " + currentMonth + " " + emailInfo.Day + "-го з " +
                       emailInfo.FromHour + " по " + emailInfo.ToHour + "<br>" +
                       "Місце: " + emailInfo.Place + "<br>" +
                       "Контактна особа Андрій - 093 23 23 432" + "<br>" +
                       "https://www.facebook.com/andrew.brunets"
            };

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync("smtp.gmail.com", 465, true);

                await client.AuthenticateAsync("*****@*****.**", _config["Gmail"]);

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }

            return(RedirectToAction("GetByUser", "Orders"));
        }
Exemplo n.º 13
0
        public static async Task SendEmailAsync(string email, string subject, string message)
        {
            Program.MedialynxData.historyDBAPI.Add(
                new HistoryItem(
                    "unknown",
                    "unknown",
                    "Mailing Service",
                    "SendEmailAsync called for: " + email
                    )
                );


            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Medalynx", "*****@*****.**"));
            emailMessage.To.Add(new MailboxAddress("", email));
            emailMessage.Subject = subject;
            emailMessage.Body    = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = message
            };

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync("smtp.yandex.ru", 25, false);

                await client.AuthenticateAsync("*****@*****.**", "m1llions");

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }
        }
Exemplo n.º 14
0
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender));

                mimeMessage.To.Add(new MailboxAddress(email));

                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = message
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true);

                    await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
        public async Task SendEmailAsync(MailRequest request)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
                message.To.Add(new MailboxAddress("", request.Email));
                message.Subject = request.Tema;
                message.Body    = new TextPart("html")
                {
                    Text = request.Cuerpo
                };

                using (var cliente = new MailKit.Net.Smtp.SmtpClient())
                {
                    await cliente.ConnectAsync(_smtpSettings.Server);

                    await cliente.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);

                    await cliente.SendAsync(message);

                    await cliente.DisconnectAsync(true);
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 16
0
        public async Task <EmailMessageResult> SendAsync(IEmailMessage message, IEmailConfiguration emailConfiguration)
        {
            try
            {
                MimeMessage mailMessage = GetInternetAddress(message);
                // check if email configuration has been set if not throw an exception
                if (emailConfiguration == null)
                {
                    throw new EmailConfigurationNotFoundException("Email Configuration is not set");
                }

                using (var emailClient = new MailKit.Net.Smtp.SmtpClient())
                {
                    await ConnectToServer(emailConfiguration, emailClient);

                    await emailClient.SendAsync(mailMessage);

                    //message was successful update the status of the EmailMessageResult object
                    messageResult.Status = Status.Success;
                    await emailClient.DisconnectAsync(true);

                    return(messageResult);
                }
            }
            catch (EmailMessageNotFoundException ex)
            {
                SetExceptionResult <EmailMessageNotFoundException>(ex);
                return(messageResult);
            }
            catch (EmailToAddressNotFoundException ex)
            {
                SetExceptionResult <EmailToAddressNotFoundException>(ex);
                return(messageResult);
            }
            catch (EmailFromAddressNotFoundException ex)
            {
                SetExceptionResult <EmailFromAddressNotFoundException>(ex);
                return(messageResult);
            }
            catch (EmailSubjectNotFoundException ex)
            {
                SetExceptionResult <EmailSubjectNotFoundException>(ex);
                return(messageResult);
            }
            catch (EmailConfigurationNotFoundException ex)
            {
                SetExceptionResult <EmailConfigurationNotFoundException>(ex);
                return(messageResult);
            }
            catch (System.Exception ex)
            {
                var emailConnectionException = new EmailConnectionException(ex.Message, ex);
                SetExceptionResult <EmailConnectionException>(emailConnectionException);
                return(messageResult);
            }
        }
Exemplo n.º 17
0
        public async Task <bool> TrySendSimpleMail(string message, string subject, string from, string to, bool isFeatureRequest,
                                                   string userName = null)
        {
            string host     = Environment.GetEnvironmentVariable("smtp_host") ?? "email-smtp.us-east-1.amazonaws.com";
            int    port     = 465;
            string username = Environment.GetEnvironmentVariable("smtp_username") ?? "AKIAQJ5VEXSPIW2KZFML";
            string password = Environment.GetEnvironmentVariable("smtp_password") ?? "BLeY+4P49vnOytQ4c8Bt/JTjAIYBBKeuPLzKtv/dMaIh";

            bool invalidInputs = SomeInputsAreInvalid(message, subject, from, to, username, password, host, port.ToString());

            if (invalidInputs)
            {
                return(false);
            }

            try
            {
                if (isFeatureRequest)
                {
                    subject = $"FEATURE REQUEST : {subject} from {from}";
                }
                else
                {
                    subject = $"ISSUE REPORT : {subject} from {from}";
                }

                string fromTranspose = from.Transpose();

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.Sender = MailboxAddress.Parse(fromTranspose);
                mailMessage.From.Add(mailMessage.Sender);
                mailMessage.To.Add(MailboxAddress.Parse(to));
                mailMessage.Subject = subject;

                BodyBuilder bodyBuilder = new BodyBuilder();
                bodyBuilder.TextBody = message;

                mailMessage.Body = bodyBuilder.ToMessageBody();


                using (MailKit.Net.Smtp.SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient())
                {
                    await smtpClient.ConnectAsync(host, port, MailKit.Security.SecureSocketOptions.Auto);

                    await smtpClient.AuthenticateAsync(new NetworkCredential(username, password));

                    await smtpClient.SendAsync(mailMessage);

                    await smtpClient.DisconnectAsync(true);

                    return(true);
                }
            }
            catch (Exception ex) { return(false); }
        }
Exemplo n.º 18
0
        public async Task MailKit_NonSSL_StressTest()
        {
            using (DefaultServer server = new DefaultServer(false, StandardSmtpPort.AssignAutomatically))
            {
                ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>();

                server.MessageReceivedEventHandler += (o, ea) =>
                {
                    messages.Add(ea.Message);
                    return(Task.CompletedTask);
                };
                server.Start();

                List <Task> sendingTasks = new List <Task>();

                int numberOfThreads           = 10;
                int numberOfMessagesPerThread = 50;

                for (int threadId = 0; threadId < numberOfThreads; threadId++)
                {
                    int localThreadId = threadId;

                    sendingTasks.Add(Task.Run(async() =>
                    {
                        using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
                        {
                            await client.ConnectAsync("localhost", server.PortNumber).ConfigureAwait(false);

                            for (int i = 0; i < numberOfMessagesPerThread; i++)
                            {
                                MimeMessage message = NewMessage(i + "@" + localThreadId, "*****@*****.**");

                                await client.SendAsync(message).ConfigureAwait(false);
                            }

                            await client.DisconnectAsync(true).ConfigureAwait(false);
                        }
                    }));
                }

                await Task.WhenAll(sendingTasks).WithTimeout(120, "sending messages").ConfigureAwait(false);

                Assert.Equal(numberOfMessagesPerThread * numberOfThreads, messages.Count);

                for (int threadId = 0; threadId < numberOfThreads; threadId++)
                {
                    for (int i = 0; i < numberOfMessagesPerThread; i++)
                    {
                        Assert.Contains(messages, m => m.Recipients.Any(t => t == i + "@" + threadId));
                    }
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="server">The server<see cref="DefaultServer"/></param>
        /// <param name="toAddress">The toAddress<see cref="string"/></param>
        /// <returns>A <see cref="Task{T}"/> representing the async operation</returns>
        private async Task SendMessage_MailKit_Async(DefaultServer server, string toAddress, string fromAddress = "*****@*****.**")
        {
            MimeMessage message = NewMessage(toAddress, fromAddress);

            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient(new SmtpClientLogger(this.output)))
            {
                await client.ConnectAsync("localhost", server.PortNumber).ConfigureAwait(false);

                await client.SendAsync(new FormatOptions { International = true }, message).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Exemplo n.º 20
0
        private async Task SendMailAsync(MimeMessage mail)
        {
            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                var ssl = _emailSettings.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None;
                await smtp.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, ssl);

                await smtp.AuthenticateAsync(_emailSettings.SenderEmail, _emailSettings.Password);

                await smtp.SendAsync(mail);

                await smtp.DisconnectAsync(true);
            };
        }
Exemplo n.º 21
0
        static async Task RunClientAsync(
            string name,
            int limit            = Int32.MaxValue,
            bool forceConnection = true,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = MimeKit.MimeMessage.Load(ParserOptions.Default, @"C:\Dev\Enron Corpus\maildir\allen-p\inbox\31_");

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            using (var smtpClient = new SmtpClient())
            {
                var counter = 1;
                while (limit-- > 0 && cancellationToken.IsCancellationRequested == false)
                {
                    try
                    {
                        if (smtpClient.IsConnected == false)
                        {
                            await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                            if (smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
                            {
                                await smtpClient.AuthenticateAsync("user", "password", cancellationToken);
                            }
                        }

                        //await SendMessageAsync(smtpClient, name, counter, cancellationToken);
                        await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    if (forceConnection)
                    {
                        await smtpClient.DisconnectAsync(true, cancellationToken);
                    }

                    counter++;
                }
            }

            stopwatch.Stop();

            Console.WriteLine("Finished. Time Taken {0}ms", stopwatch.ElapsedMilliseconds);
        }
Exemplo n.º 22
0
        public async Task Send(MailData data)
        {
            using var client = new SmtpClient();
            await client.ConnectAsync(_emailOptions.Host, _emailOptions.Port, true);

            if (client.Capabilities.HasFlag(SmtpCapabilities.Authentication))
            {
                await client.AuthenticateAsync(_emailOptions.Login, _emailOptions.Password);
            }

            await client.SendAsync(GetMessage(data));

            await client.DisconnectAsync(true);
        }
Exemplo n.º 23
0
        public async Task SendEmail(MimeMessage message)
        {
            var data = GetData();

            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                await client.ConnectAsync(data.Server, data.Port, data.SSL);

                await client.AuthenticateAsync(data.Username, data.Password);

                await client.SendAsync(message);

                await client.DisconnectAsync(true);
            }
        }
Exemplo n.º 24
0
        public async Task <ActionResult> AppointmentResultTest(int?id, int?serviceId)
        {
            ApplicationUser user = db.Users.Find(User.Identity.GetUserId());

            if (id != null && user != null)
            {
                Record        record        = db.Records.Find(id);
                TypeOfService typeOfService = db.TypeOfServices.Find(serviceId);
                record.TypeOfServiceId = serviceId;
                record.PatientId       = user.Id;
                db.SaveChanges();
                // настройка логина, пароля отправителя
                var from = "*****@*****.**";
                var pass = "******";

                // создаем письмо: message.Destination - адрес получателя
                var emailMessage = new MimeMessage()
                {
                    Subject = "eLife підтвердження запису",
                    Body    = new TextPart(MimeKit.Text.TextFormat.Html)
                    {
                        Text = "<h2> " + record.Patient.Name + " , ви успішно записались на прийом" + " </h2> <br>"
                               + "<h3> Лікар:" + record.AttendingDoctor.Name + " </h3><br>" +
                               "< h3 > Клініка:" + record.AttendingDoctor.DoctorInform.Clinic.Name + " </ h3 >< br > " +
                               "< h3 > Дата та час:" + record.Date + " </ h3 >< br > " +
                               "< h3 > Вид прийому:" + record.TypeOfService.Name + " </ h3 >< br > "
                    }
                };
                emailMessage.From.Add(new MailboxAddress("Администрация сайта", from));
                emailMessage.To.Add(new MailboxAddress("", record.Patient.Email));

                // адрес и порт smtp-сервера, с которого мы и будем отправлять письмо
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync("smtp.gmail.com", 465);

                    await client.AuthenticateAsync(from, pass);

                    await client.SendAsync(emailMessage);

                    await client.DisconnectAsync(true);
                }
                ViewBag.Type = record.TypeOfService.Name;
                return(View("AppointmentResult", record));
            }
            return(View("~/Views/Shared/_Error.cshtml"));
        }
Exemplo n.º 25
0
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender));

                mimeMessage.To.Add(new MailboxAddress(email));

                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = message
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    if (_env.IsDevelopment())
                    {
                        // The third parameter is useSSL (true if the client should make an SSL-wrapped
                        // connection to the server; otherwise, false).
                        await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, MailKit.Security.SecureSocketOptions.StartTls);
                    }
                    else
                    {
                        await client.ConnectAsync(_emailSettings.MailServer);
                    }

                    // Note: only needed if the SMTP server requires authentication
                    await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception ex)
            {
                // TODO: handle exception
                throw new InvalidOperationException(ex.Message);
            }
        }
Exemplo n.º 26
0
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender));

                mimeMessage.To.Add(new MailboxAddress(email));

                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = message
                };

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    if (_env.IsDevelopment())
                    {
                        await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, SecureSocketOptions.StartTls);
                    }
                    else
                    {
                        await client.ConnectAsync(_emailSettings.MailServer);
                    }

                    await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    Console.WriteLine($"Email sent successfully!\nFrom: {mimeMessage.From}, To: {mimeMessage.To}");

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception ex)
            {
                // TODO: handle exception
                //throw new InvalidOperationException(ex.Message);
                Console.WriteLine($"Error while sending email\nException: {ex.ToString()}");
            }
        }
Exemplo n.º 27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="server">The server<see cref="DefaultServer"/></param>
        /// <param name="toAddress">The toAddress<see cref="string"/></param>
        /// <returns>A <see cref="Task{T}"/> representing the async operation</returns>
        private async Task SendMessage_MailKit_Async(DefaultServer server, string toAddress, string fromAddress = "*****@*****.**", MailKit.Security.SecureSocketOptions secureSocketOptions = MailKit.Security.SecureSocketOptions.None)
        {
            MimeMessage message = NewMessage(toAddress, fromAddress);

            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient(new SmtpClientLogger(this.output)))
            {
                client.CheckCertificateRevocation          = false;
                client.ServerCertificateValidationCallback = (mysender, certificate, chain, sslPolicyErrors) => {
                    return(true);
                };
                client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                await client.ConnectAsync("localhost", server.PortNumber, secureSocketOptions).ConfigureAwait(false);

                await client.SendAsync(new FormatOptions { International = true }, message).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Exemplo n.º 28
0
        public async Task SendEmailAsync(string[] toEmails, string subject, string htmlMessage)
        {
            if (toEmails is null)
            {
                throw new ArgumentNullException(nameof(toEmails));
            }

            if (string.IsNullOrEmpty(subject))
            {
                throw new ArgumentException($"'{nameof(subject)}' cannot be null or empty", nameof(subject));
            }

            if (string.IsNullOrEmpty(htmlMessage))
            {
                throw new ArgumentException($"'{nameof(htmlMessage)}' cannot be null or empty", nameof(htmlMessage));
            }

            var message = new MimeMessage();

            message.From.Add(MailboxAddress.Parse("*****@*****.**"));
            foreach (var toEmail in toEmails)
            {
                message.To.Add(MailboxAddress.Parse(toEmail));
            }

            message.Subject = subject;
            message.Body    = new TextPart(TextFormat.Html)
            {
                Text = htmlMessage
            };

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync("smtp.qq.com", 587, false).ConfigureAwait(false);

                //QQ邮件授权码  dglslhzvyexibebc
                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "daoyjawyifxabejf");

                await client.SendAsync(message).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Exemplo n.º 29
0
        static async Task RunFolderAsync(string folder, string pattern = "*", CancellationToken cancellationToken = default(CancellationToken))
        {
            foreach (var directory in Directory.GetDirectories(folder, "*", SearchOption.AllDirectories))
            {
                Console.WriteLine(directory);
                cancellationToken.ThrowIfCancellationRequested();

                foreach (var file in Directory.GetFiles(directory, pattern).ToList())
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    Console.WriteLine(new FileInfo(file).Name);

                    MimeKit.MimeMessage message;
                    try
                    {
                        message = MimeKit.MimeMessage.Load(ParserOptions.Default, file);
                    }
                    catch
                    {
                        continue;
                    }

                    using (var smtpClient = new SmtpClient())
                    {
                        try
                        {
                            await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                            await smtpClient.AuthenticateAsync("user", "password", cancellationToken);

                            await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                        }

                        await smtpClient.DisconnectAsync(true, cancellationToken);
                    }
                }
            }
        }
Exemplo n.º 30
0
        static async Task RunClientAsync(string name, int maximum = Int32.MaxValue, CancellationToken cancellationToken = default(CancellationToken))
        {
            var counter = 0;

            while (counter++ < maximum && cancellationToken.IsCancellationRequested == false)
            {
                using (var smtpClient = new SmtpClient())
                {
                    await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                    Console.WriteLine();
                    Console.WriteLine("Client has Connected.");
                    Console.WriteLine(smtpClient.Capabilities);
                    Console.WriteLine(smtpClient.IsSecure);
                    Console.WriteLine();

                    try
                    {
                        var message = new MimeKit.MimeMessage();
                        message.From.Add(new MimeKit.MailboxAddress($"{name}{counter}@test.com"));
                        message.To.Add(new MimeKit.MailboxAddress("*****@*****.**"));
                        message.Subject = $"Subject test çãõáéíóú";

                        message.Body = new TextPart(TextFormat.Plain)
                        {
                            Text = "Test Message Body special char çãõáéíóú",
                        };

                        await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    await smtpClient.DisconnectAsync(true, cancellationToken);
                }

                counter++;
            }
        }
Exemplo n.º 31
0
        static async Task RunFileAsync(string file, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = MimeKit.MimeMessage.Load(ParserOptions.Default, file);

            using (var smtpClient = new SmtpClient())
            {
                try
                {
                    await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                    await smtpClient.AuthenticateAsync("user", "password", cancellationToken);

                    await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }

                await smtpClient.DisconnectAsync(true, cancellationToken);
            }
        }
Exemplo n.º 32
0
        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrEmpty(to))
            {
                throw new ArgumentException("no to address provided");
            }

            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrEmpty(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            if (string.IsNullOrEmpty(plainTextMessage) && string.IsNullOrEmpty(htmlMessage))
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();
           
            m.From.Add(new MailboxAddress("", from));
            m.To.Add(new MailboxAddress("", to));
            m.Subject = subject;
            //m.Importance = MessageImportance.Normal;
            //Header h = new Header(HeaderId.Precedence, "Bulk");
            //m.Headers.Add()

            BodyBuilder bodyBuilder = new BodyBuilder();
            if(plainTextMessage.Length > 0)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (htmlMessage.Length > 0)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();
            
            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync(
                    smtpOptions.Server, 
                    smtpOptions.Port, 
                    smtpOptions.UseSsl)
                    .ConfigureAwait(false);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if(smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password)
                        .ConfigureAwait(false);
                }
                
                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }
Exemplo n.º 33
0
		private async Task SendEmailAsync(MimeMessage emailMessage, SmtpOptions smtpOption)
		{
			using (var client = new SmtpClient())
			{
				await client.ConnectAsync(smtpOption.Server, smtpOption.Port, smtpOption.UseSsl)
					.ConfigureAwait(false);

				// Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
				client.AuthenticationMechanisms.Remove("XOAUTH2");

				// Note: only needed if the SMTP server requires authentication.
				if (smtpOption.RequiresAuthentication)
				{
					await client.AuthenticateAsync(smtpOption.User, smtpOption.Password)
						.ConfigureAwait(false);
				}

				await client.SendAsync(emailMessage).ConfigureAwait(false);
				await client.DisconnectAsync(true).ConfigureAwait(false);
			}
		}
Exemplo n.º 34
0
		public async void TestBinaryMime ()
		{
			var message = CreateBinaryMessage ();
			string bdat;

			using (var memory = new MemoryStream ()) {
				var options = FormatOptions.Default.Clone ();
				long size;

				options.NewLineFormat = NewLineFormat.Dos;

				using (var measure = new MeasuringStream ()) {
					message.WriteTo (options, measure);
					size = measure.Length;
				}

				var bytes = Encoding.ASCII.GetBytes (string.Format ("BDAT {0} LAST\r\n", size));
				memory.Write (bytes, 0, bytes.Length);
				message.WriteTo (options, memory);

				bytes = memory.GetBuffer ();

				bdat = Encoding.UTF8.GetString (bytes, 0, (int) memory.Length);
			}

			var commands = new List<SmtpReplayCommand> ();
			commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+binarymime.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**> BODY=BINARYMIME\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt"));
			commands.Add (new SmtpReplayCommand (bdat, "comcast-data-done.txt"));
			commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt"));

			using (var client = new SmtpClient ()) {
				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands));
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Client failed to connect.");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension");
				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension");
				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension");
				Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly");
				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension");

				try {
					await client.AuthenticateAsync ("username", "password");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
				}

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime), "Failed to detect BINARYMIME extension");
				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Chunking), "Failed to detect CHUNKING extension");

				try {
					await client.SendAsync (message);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Send: {0}", ex);
				}

				try {
					await client.DisconnectAsync (true);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex);
				}

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Exemplo n.º 35
0
		public async void TestRcptToMailboxUnavailable ()
		{
			var commands = new List<SmtpReplayCommand> ();
			commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "mailbox-unavailable.txt"));
			commands.Add (new SmtpReplayCommand ("RSET\r\n", "comcast-rset.txt"));
			commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt"));

			using (var client = new SmtpClient ()) {
				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands));
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Client failed to connect.");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension");
				Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension");

				try {
					await client.AuthenticateAsync ("username", "password");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
				}

				try {
					await client.SendAsync (CreateSimpleMessage ());
					Assert.Fail ("Expected an SmtpException");
				} catch (SmtpCommandException sex) {
					Assert.AreEqual (sex.ErrorCode, SmtpErrorCode.RecipientNotAccepted, "Unexpected SmtpErrorCode");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect this exception in Send: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Expected the client to still be connected");

				try {
					await client.DisconnectAsync (true);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex);
				}

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Exemplo n.º 36
0
		public async void TestBasicFunctionality ()
		{
			var commands = new List<SmtpReplayCommand> ();
			commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO unit-tests.mimekit.org\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("VRFY Smith\r\n", "rfc0821-vrfy.txt"));
			commands.Add (new SmtpReplayCommand ("EXPN Example-People\r\n", "rfc0821-expn.txt"));
			commands.Add (new SmtpReplayCommand ("NOOP\r\n", "comcast-noop.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt"));
			commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt"));
			commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt"));
			commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt"));
			commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt"));
			commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt"));
			commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt"));
			commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt"));
			commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt"));
			commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt"));

			using (var client = new SmtpClient ()) {
				client.LocalDomain = "unit-tests.mimekit.org";

				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands));
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Client failed to connect.");
				Assert.IsFalse (client.IsSecure, "IsSecure should be false.");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension");
				Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension");

				Assert.Throws<ArgumentException> (() => client.Capabilities |= SmtpCapabilities.UTF8);

				Assert.AreEqual (100000, client.Timeout, "Timeout");
				client.Timeout *= 2;

				try {
					await client.AuthenticateAsync ("username", "password");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
				}

				try {
					await client.VerifyAsync ("Smith");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Verify: {0}", ex);
				}

				try {
					await client.ExpandAsync ("Example-People");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Expand: {0}", ex);
				}

				try {
					await client.NoOpAsync ();
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in NoOp: {0}", ex);
				}

				var message = CreateSimpleMessage ();
				var options = FormatOptions.Default;

				try {
					await client.SendAsync (message);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Send: {0}", ex);
				}

				try {
					await client.SendAsync (message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Send: {0}", ex);
				}

				try {
					await client.SendAsync (options, message);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Send: {0}", ex);
				}

				try {
					await client.SendAsync (options, message, message.From.Mailboxes.FirstOrDefault (), message.To.Mailboxes);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Send: {0}", ex);
				}

				try {
					await client.DisconnectAsync (true);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex);
				}

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Exemplo n.º 37
0
		public async void TestInvalidStateExceptions ()
		{
			var commands = new List<SmtpReplayCommand> ();
			commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "auth-required.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "auth-required.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "auth-required.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt"));
			commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "auth-required.txt"));
			commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt"));

			using (var client = new SmtpClient ()) {
				var message = CreateSimpleMessage ();
				var sender = message.From.Mailboxes.FirstOrDefault ();
				var recipients = message.To.Mailboxes.ToList ();
				var options = FormatOptions.Default;

				client.LocalDomain = "127.0.0.1";

				Assert.Throws<ServiceNotConnectedException> (async () => await client.AuthenticateAsync ("username", "password"));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.AuthenticateAsync (new NetworkCredential ("username", "password")));

				Assert.Throws<ServiceNotConnectedException> (async () => await client.NoOpAsync ());

				Assert.Throws<ServiceNotConnectedException> (async () => await client.SendAsync (options, message, sender, recipients));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.SendAsync (message, sender, recipients));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.SendAsync (options, message));
				Assert.Throws<ServiceNotConnectedException> (async () => await client.SendAsync (message));

				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands));
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
				}

				Assert.Throws<InvalidOperationException> (async () => await client.ConnectAsync ("host", 465, SecureSocketOptions.SslOnConnect));
				Assert.Throws<InvalidOperationException> (async () => await client.ConnectAsync ("host", 465, true));

				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.SendAsync (options, message, sender, recipients));
				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.SendAsync (message, sender, recipients));
				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.SendAsync (options, message));
				Assert.Throws<ServiceNotAuthenticatedException> (async () => await client.SendAsync (message));

				try {
					await client.AuthenticateAsync ("username", "password");
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
				}

				Assert.Throws<InvalidOperationException> (async () => await client.AuthenticateAsync ("username", "password"));
				Assert.Throws<InvalidOperationException> (async () => await client.AuthenticateAsync (new NetworkCredential ("username", "password")));

				await client.DisconnectAsync (true);
			}
		}
Exemplo n.º 38
0
		public async void TestUnauthorizedAccessException ()
		{
			var commands = new List<SmtpReplayCommand> ();
			commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt"));
			commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt"));
			commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "auth-required.txt"));
			commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt"));

			using (var client = new SmtpClient ()) {
				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands));
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Client failed to connect.");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism");
				Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension");
				Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly");

				Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension");

				try {
					await client.SendAsync (CreateSimpleMessage ());
					Assert.Fail ("Expected an ServiceNotAuthenticatedException");
				} catch (ServiceNotAuthenticatedException) {
					// this is the expected exception
				} catch (Exception ex) {
					Assert.Fail ("Did not expect this exception in Send: {0}", ex);
				}

				Assert.IsTrue (client.IsConnected, "Expected the client to still be connected");

				try {
					await client.DisconnectAsync (true);
				} catch (Exception ex) {
					Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex);
				}

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Exemplo n.º 39
0
        public async Task SendMultipleEmailAsync(
            SmtpOptions smtpOptions,
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrWhiteSpace(toCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage);
            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }




            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));

            string[] adrs = toCsv.Split(',');

            foreach (string item in adrs)
            {
                if (!string.IsNullOrEmpty(item)) { m.To.Add(new MailboxAddress("", item)); ; }
            }

            m.Subject = subject;
            m.Importance = MessageImportance.High;

            BodyBuilder bodyBuilder = new BodyBuilder();
            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl).ConfigureAwait(false);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(
                        smtpOptions.User,
                        smtpOptions.Password).ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }
Exemplo n.º 40
-1
		public async Task SendMessage(MailAccount fromAccount, string messageText, params string[] receipients)
		{
			MimeKit.MimeMessage message = new MimeKit.MimeMessage();
			message.From.Add(fromAccount.Address);
			for (int i = 0; i < receipients.Length; i++)
			{
				message.To.Add (new MailboxAddress(receipients [i], receipients [i]));
			}

			message.Subject = string.Format("[OpenFlow {0}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zz"));
			message.Body = new MimeKit.TextPart("plain") {
				Text = messageText
			};

			SmtpClient client = new SmtpClient();
			await client.ConnectAsync(fromAccount.SmtpAddress, fromAccount.SmtpPort, SecureSocketOptions.StartTls);
			try
			{
				client.AuthenticationMechanisms.Remove ("XOAUTH2");
				await client.AuthenticateAsync(fromAccount.Address.Address, fromAccount.Password);
				await client.SendAsync(message);
			}
			finally
			{
				await client.DisconnectAsync(true);	
			}
		}