Beispiel #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;
            }
           
        }
Beispiel #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();
                }
            }
        }
Beispiel #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);
            }
        }
        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 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)
            {
            }
        }
        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();
                }
            }
        }
Beispiel #7
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();
                }
            }
        }
Beispiel #8
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();
                }
            }
        }
Beispiel #9
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);
            }
        }
Beispiel #10
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 <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));
        }
        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);
            }
        }
Beispiel #13
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);
            }
        }
Beispiel #14
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);
        }
        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"));
        }
Beispiel #16
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); }
        }
Beispiel #17
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);
        }
Beispiel #18
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);
            };
        }
Beispiel #19
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);
        }
        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);
            }
        }
Beispiel #21
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"));
        }
Beispiel #22
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()}");
            }
        }
Beispiel #23
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);
            }
        }
Beispiel #24
0
    protected virtual async Task ConfigureClient(SmtpClient client)
    {
        await client.ConnectAsync(
            await SmtpConfiguration.GetHostAsync(),
            await SmtpConfiguration.GetPortAsync(),
            await GetSecureSocketOption()
            );

        if (await SmtpConfiguration.GetUseDefaultCredentialsAsync())
        {
            return;
        }

        await client.AuthenticateAsync(
            await SmtpConfiguration.GetUserNameAsync(),
            await SmtpConfiguration.GetPasswordAsync()
            );
    }
Beispiel #25
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);
                    }
                }
            }
        }
Beispiel #26
0
        private async static Task SmtpMailKitAsync()
        {
            MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient();
            await client.ConnectAsync("imap.gmail.com", 587);

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

            var mail = new MimeMessage();

            mail.From.Add(new MailboxAddress("*****@*****.**"));
            mail.To.Add(new MailboxAddress("bob@gmail,com"));
            mail.Subject = "MAilKit test smtp";
            var builder = new BodyBuilder();

            builder.TextBody = "HEllo";
            mail.Body        = builder.ToMessageBody();
            await client.SendAsync(mail);

            Console.WriteLine("Compleated...");
        }
        public async Task <bool> SendAsync(string subject, string message, SenderTypes senderType, string receiverEmail)
        {
            EmailSender emailConfigurationSender = _emailConfiguration.Senders.FirstOrDefault(x => x.Type.Equals(senderType));

            if (emailConfigurationSender == null)
            {
                return(false);
            }

            using (SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(_emailConfiguration.Host, _emailConfiguration.Port);

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

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

                await client.SendAsync(mailMessage);

                await client.DisconnectAsync(true);
            }

            return(true);
        }
Beispiel #28
0
        public static async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("mgaon", "*****@*****.**"));
            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("webmail.active.by", 25, false);

                await client.AuthenticateAsync("*****@*****.**", "7632bxr29ZX6");

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }
        }
        public async Task SendEmail(string Email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Администрация 4 Лаборатоной", "*****@*****.**"));
            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("*****@*****.**", "162534iva");

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }
        }
Beispiel #30
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);
            }
        }
Beispiel #31
0
        public async Task <bool> SendAsync(object value)
        {
            viEmailModel email = value as viEmailModel;

            logger.LogInformation($"Send EMAIL to {email.ToEmail}");
            return(await ValueTask.FromResult(true));

            var fromEmail  = conf["EmailSender:SMTPAccount"];
            var smtpServer = conf["EmailSender:SMTPServer"];
            var smtpPort   = conf["EmailSender:SMTPPort"];
            var smtpPassw  = conf["EmailSender:SMTPPassword"];


            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Admin Quote service", fromEmail));
            emailMessage.To.Add(new MailboxAddress("User", email.ToEmail));
            emailMessage.Subject = email.Subject;

            var bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = email.Body;

            emailMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(smtpServer, smtpPort.ToInt());

                await client.AuthenticateAsync(fromEmail, smtpPassw);

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }

            return(true);
        }
Beispiel #32
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);
			}
		}
		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);
			}
		}
Beispiel #34
0
        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            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);
                //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);
                }
                
                client.Send(m);
                client.Disconnect(true);
            }

        }
		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");
			}
		}
		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");
			}
		}
		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");
			}
		}
Beispiel #38
0
        public async Task SendMultipleEmailAsync(
            SmtpOptions smtpOptions,
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrEmpty(toCsv))
            {
                throw new ArgumentException("no to addresses 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));

            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 (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);
            }

        }
Beispiel #39
-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);	
			}
		}
		public void TestArgumentExceptions ()
		{
			using (var client = new SmtpClient ()) {
				var credentials = new NetworkCredential ("username", "password");
				var socket = new Socket (SocketType.Stream, ProtocolType.Tcp);
				var message = CreateSimpleMessage ();
				var sender = message.From.Mailboxes.FirstOrDefault ();
				var recipients = message.To.Mailboxes.ToList ();
				var options = FormatOptions.Default;
				var empty = new MailboxAddress[0];

				// Connect
				Assert.Throws<ArgumentNullException> (() => client.Connect ((Uri) null));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync ((Uri) null));
				Assert.Throws<ArgumentNullException> (() => client.Connect (null, 25, false));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync (null, 25, false));
				Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 25, false));
				Assert.Throws<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 25, false));
				Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, false));
				Assert.Throws<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, false));
				Assert.Throws<ArgumentNullException> (() => client.Connect (null, 25, SecureSocketOptions.None));
				Assert.Throws<ArgumentNullException> (async () => await client.ConnectAsync (null, 25, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (() => client.Connect (string.Empty, 25, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (async () => await client.ConnectAsync (string.Empty, 25, SecureSocketOptions.None));
				Assert.Throws<ArgumentOutOfRangeException> (() => client.Connect ("host", -1, SecureSocketOptions.None));
				Assert.Throws<ArgumentOutOfRangeException> (async () => await client.ConnectAsync ("host", -1, SecureSocketOptions.None));

				Assert.Throws<ArgumentNullException> (() => client.Connect (null, "host", 25, SecureSocketOptions.None));
				Assert.Throws<ArgumentException> (() => client.Connect (socket, "host", 25, SecureSocketOptions.None));

				// Authenticate
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, "password"));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null, "password"));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate ("username", null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync ("username", null));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, credentials));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null, credentials));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, null));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (null, "username", "password"));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (null, "username", "password"));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, null, "password"));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, null, "password"));
				Assert.Throws<ArgumentNullException> (() => client.Authenticate (Encoding.UTF8, "username", null));
				Assert.Throws<ArgumentNullException> (async () => await client.AuthenticateAsync (Encoding.UTF8, "username", null));

				// Send
				Assert.Throws<ArgumentNullException> (() => client.Send (null));

				Assert.Throws<ArgumentNullException> (() => client.Send (null, message));
				Assert.Throws<ArgumentNullException> (() => client.Send (options, null));

				Assert.Throws<ArgumentNullException> (() => client.Send (message, null, recipients));
				Assert.Throws<ArgumentNullException> (() => client.Send (message, sender, null));
				Assert.Throws<InvalidOperationException> (() => client.Send (message, sender, empty));

				Assert.Throws<ArgumentNullException> (() => client.Send (null, message, sender, recipients));
				Assert.Throws<ArgumentNullException> (() => client.Send (options, message, null, recipients));
				Assert.Throws<ArgumentNullException> (() => client.Send (options, message, sender, null));
				Assert.Throws<InvalidOperationException> (() => client.Send (options, message, sender, empty));

				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (null));

				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (null, message));
				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (options, null));

				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (message, null, recipients));
				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (message, sender, null));
				Assert.Throws<InvalidOperationException> (async () => await client.SendAsync (message, sender, empty));

				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (null, message, sender, recipients));
				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (options, message, null, recipients));
				Assert.Throws<ArgumentNullException> (async () => await client.SendAsync (options, message, sender, null));
				Assert.Throws<InvalidOperationException> (async () => await client.SendAsync (options, message, sender, empty));

				// Expand
				Assert.Throws<ArgumentNullException> (() => client.Expand (null));
				Assert.Throws<ArgumentException> (() => client.Expand (string.Empty));
				Assert.Throws<ArgumentException> (() => client.Expand ("line1\r\nline2"));
				Assert.Throws<ArgumentNullException> (async () => await client.ExpandAsync (null));
				Assert.Throws<ArgumentException> (async () => await client.ExpandAsync (string.Empty));
				Assert.Throws<ArgumentException> (async () => await client.ExpandAsync ("line1\r\nline2"));

				// Verify
				Assert.Throws<ArgumentNullException> (() => client.Verify (null));
				Assert.Throws<ArgumentException> (() => client.Verify (string.Empty));
				Assert.Throws<ArgumentException> (() => client.Verify ("line1\r\nline2"));
				Assert.Throws<ArgumentNullException> (async () => await client.VerifyAsync (null));
				Assert.Throws<ArgumentException> (async () => await client.VerifyAsync (string.Empty));
				Assert.Throws<ArgumentException> (async () => await client.VerifyAsync ("line1\r\nline2"));
			}
		}