Connect() public method

Establish a connection to the specified SMTP or SMTP/S server using the provided socket.

Establishes a connection to the specified SMTP or SMTP/S server.

If the port has a value of 0, then the options parameter is used to determine the default port to connect to. The default port used with SecureSocketOptions.SslOnConnect is 465. All other values will use a default port of 25.

If the options has a value of SecureSocketOptions.Auto, then the port is used to determine the default security options. If the port has a value of 465, then the default options used will be SecureSocketOptions.SslOnConnect. All other values will use SecureSocketOptions.StartTlsWhenAvailable.

Once a connection is established, properties such as AuthenticationMechanisms and Capabilities will be populated.

The connection established by any of the Connect methods may be re-used if an application wishes to send multiple messages to the same SMTP server. Since connecting and authenticating can be expensive operations, re-using a connection can significantly improve performance when sending a large number of messages to the same SMTP server over a short period of time./
/// is null. /// -or- /// is null. /// /// is not between 0 and 65535. /// /// is not connected. /// -or- /// The is a zero-length string. /// /// The has been disposed. /// /// The is already connected. /// /// was set to /// /// and the SMTP server does not support the STARTTLS extension. /// /// The operation was canceled. /// /// An I/O error occurred. /// /// An SMTP command failed. /// /// An SMTP protocol error occurred. ///
public Connect ( StreamSocket socket, string host, int port, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken) ) : void
socket Windows.Networking.Sockets.StreamSocket The socket to use for the connection.
host string The host name to connect to.
port int The port to connect to. If the specified port is 0, then the default port will be used.
options SecureSocketOptions The secure socket options to when connecting.
cancellationToken System.Threading.CancellationToken The cancellation token.
return void
示例#1
3
        public void Send(EmailDependencies email)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.To.Add(new MailboxAddress(email.ToName, email.ToAddress));
                message.To.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.Subject = email.Title;
                message.Body = new TextPart("html") { Text = email.content };

                using (var client = new SmtpClient())
                {
                    client.Connect("mail.bizmonger.net", 587, 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
                    client.Authenticate(Configuration.ServerEmail, Configuration.Password);

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ex.GetBaseException().Message;
                Debug.WriteLine(errorMessage);
            }
        }
示例#2
2
 public void SendMessage() {
     string msg = "";
     switch (CurrEmailType) {
         case EmailType.PRENOTA:
             msg = PrenotaSubject;
             FromMailAddress = PrenotaFromAddress;
             break;
         case EmailType.INFO:
             msg = InfoSubject;
             FromMailAddress = InfoFromAddress;
             break;
     }
     string subject = string.Format(msg, Message.Nome, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
     string body = string.Format("Nome : {0}\nNumero : {1}\nE-Mail : {2}\nMessaggio :\n{3}", Message.Nome, Message.Telefono, Message.Email, Message.Messaggio);
     var message = new MimeMessage();
     message.From.Add(FromMailAddress);
     message.To.Add(ToAddress);
     message.Subject = subject;
     message.Body = new TextPart("plain") {Text = body};
     try {
         using (var client = new SmtpClient()) {
             client.Connect("smtp.gmail.com", 465, true);
             client.AuthenticationMechanisms.Remove("XOAUTH");
             client.Authenticate("*****@*****.**", "At066bn1!");
             client.Send(message);
             client.Disconnect(true);
         }
         Result = EmailResult.SUCCESS;
         MessageResult = "Messaggio inviato correttamente";
     } catch (Exception ex) {
         Result = EmailResult.FAIL;
         MessageResult = ex.Message;
     }
 }
示例#3
1
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
                return;

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
                return;

            if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                MailLevels level;
                if (result is Exception)
                    level = MailLevels.Error;
                else if (result != null && result is Library.Interface.IBackupResults && (result as Library.Interface.IBackupResults).Errors.Count() > 0)
                    level = MailLevels.Warning;
                else
                    level = MailLevels.Success;

                m_parsedresultlevel = level.ToString();

                if (m_level != MailLevels.All)
                {
                    //Check if this level should send mail
                    if ((m_level & level) == 0)
                        return;
                }
            }

            try
            {
                string body = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.File.Exists(body))
                    body = System.IO.File.ReadAllText(body);

                body = ReplaceTemplate(body, result, false);
                subject = ReplaceTemplate(subject, result, true);

                var message = new MimeMessage();
                MailboxAddress mailbox;
                foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    if(MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox))
                        message.To.Add(mailbox);

                MailboxAddress mailboxToFirst = (MailboxAddress) message.To[0];
                string toMailDomain = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@") + 1);

                string from = m_from.Trim().Replace("\"", "");
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">"))
                        from = from.Insert(from.Length - 1, "@" + toMailDomain);
                    else
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain);
                }

                if (MailboxAddress.TryParse(from, out mailbox))
                    message.From.Add(mailbox);

                message.Subject = subject;
                message.Body = new TextPart("plain") { Text = body, ContentTransferEncoding = ContentEncoding.EightBit };

                List<string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List<string>();

                    //Grab all IPv4 adresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                        try
                        {
                            foreach (IPAddress dnsAdress in networkInterface.GetIPProperties().DnsAddresses)
                                if (dnsAdress.AddressFamily == AddressFamily.InterNetwork)
                                    dnslist.Add(dnsAdress.ToString());
                        }
                        catch { }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var oldStyleList = new ArrayList();
                    foreach(var s in dnslist)
                        oldStyleList.Add(s);

                    dnslite.setDnsServers(oldStyleList);

                    servers = dnslite.getMXRecords(toMailDomain).OfType<MXRecord>().OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                        throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                              let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n
                              where !string.IsNullOrEmpty(srv)
                              select srv).Distinct().ToList();
                }

                Exception lastEx = null;
                string lastServer = null;

                foreach(var server in servers)
                {
                    if (lastEx != null)
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx);

                    lastServer = server;
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            try
                            {
                                using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms)))
                                {
                                    client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                                    client.Connect(new System.Uri(server));

                                    if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                                        client.Authenticate(m_username, m_password);

                                    client.Send(message);
                                    client.Disconnect(true);
                                }
                            }
                            finally
                            {
                                var log = Encoding.UTF8.GetString(ms.GetBuffer());
                                Logging.Log.WriteMessage(Strings.SendMail.SendMailLog(log), LogMessageType.Profiling);
                            }
                        }

                        lastEx = null;
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailSuccess(server), LogMessageType.Information);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                    throw lastEx;
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var sb = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                        sb.Append("--> ");
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedError(sb.ToString()), LogMessageType.Warning, ex);
            }
        }
        public static void SendEmail(System.Net.Mail.MailMessage message, bool enableSsl)
        {
            try
            {
                var m = new MimeMessage();
                m.From.Add(new MailboxAddress("Forgot Password", message.From.Address));
                m.To.Add(new MailboxAddress("", message.To[0].Address));
                m.Subject = message.Subject;
                if (message.IsBodyHtml)
                    m.Body = new TextPart("html") { Text = message.Body };
                else
                    m.Body = new TextPart("plain") { Text = message.Body };

                using (var client = new SmtpClient())
                {
                    client.Connect(Settings.GetValue<string>("smtpHost"), Settings.GetValue<int>("smtpPort"), enableSsl);
                    client.Authenticate(new NetworkCredential(Settings.GetValue<string>("serverEmail"), Settings.GetValue<string>("serverEmailPassword")));
                    client.Send(m);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        private void EMSend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                buildTolist();
                if (sendTo.Length == 0 || EMservice.Text.Equals("Select One"))
                {
                    Console.WriteLine(sendTo + EMservice.Text);
                    MessageBox.Show("Check your entries");
                    return;
                }
                Console.WriteLine("to be sent to:" + sendTo.TrimEnd(','));
                var mailMessage = new MailMessage
                {
                    From    = new MailAddress(EMuser.Text),
                    Subject = EMHead.Text,
                    Body    = EMmessage.Text
                };
                mailMessage.To.Add(sendTo.TrimEnd(','));
                if (!EMattatchment.Text.Contains("Want to attatch"))
                {
                    Console.WriteLine("Attempting attachment");
                    var attachment = new Attachment(EMattatchment.Text);
                    mailMessage.Attachments.Add(attachment);
                    Console.WriteLine("attachment Complete");
                }


                Console.WriteLine("Attempting to send");
                using (var smtpClient = new SmtpClient())
                {
                    switch (EMservice.Text)
                    {
                    case "Gmail":
                        smtpClient.Connect("smtp.gmail.com", 465, true);
                        break;

                    case "ICloud":
                        smtpClient.Connect("smtp.mail.me.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);
                        break;

                    case "Office365":
                        smtpClient.Connect("smtp.office365.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);
                        break;

                    case "Outlook":
                        smtpClient.Connect("smtp.outlook.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);
                        break;
                    }
                    smtpClient.Authenticate(EMuser.Text, EMpass.Text);
                    smtpClient.Send((MimeKit.MimeMessage)mailMessage);
                    smtpClient.Disconnect(true);
                }
                MessageBox.Show("Emails sent!");
            }
            catch (Exception x)
            {
                MessageBox.Show($"Uh oh something went wrong\n {x.ToString()}", "UGH");
            }
        }
        public static bool SendMail(string mailTo, string mailTitle, string mailContent)
        {
            try
            {
                var message = new MimeMessage();
                message.To.Add(new MailboxAddress(mailTo));
                message.From.Add(new MailboxAddress("AbleMusicStudio", "*****@*****.**"));
                message.Subject = mailTitle;

                var builder = new BodyBuilder();
                builder.HtmlBody = mailContent;
                // builder.Attachments.Add(attachment);
                message.Body = builder.ToMessageBody();
                using (var emailClient = new MailKit.Net.Smtp.SmtpClient())
                {
                    emailClient.Connect("smtp.gmail.com", 587, false);
                    emailClient.Authenticate("*****@*****.**", "er345ssDl5Ddxss");
                    emailClient.Send(message);
                    emailClient.Disconnect(true);
                }

                Console.WriteLine("Email has been sent\nMail To: " + mailTo + "\n MailTitle: " + mailTitle + "\nMail Content: " + mailContent + "\n");
                return(true);
            }
            catch (Exception e)
            {
                throw e;
                // Console.WriteLine(e.Message);
                // return false;
            }
        }
示例#7
0
        public IActionResult Index()
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Hello", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Send mail asp net core", "*****@*****.**"));
            message.Subject = "Learn to send mail using asp net core";
            //message.Body = new TextPart("plain")
            //{
            //    Text = "I am using mailkit to send email with asp net core 2.2" +
            //    "<h1>HEllO<h1>"

            //};
            BodyBuilder bodyBuilder = new BodyBuilder();

            using (StreamReader SourceReader = System.IO.File.OpenText(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\TextFile.txt", "")))
            {
                bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
            }
            message.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                //client.Connect("MAIL_SERVER", 465, SecureSocketOptions.SslOnConnect);
                client.Connect("smtp.gmail.com", 587, false);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("*****@*****.**", "09041998123");
                client.Send(message);
                client.Disconnect(true);
            }

            return(View());
        }
示例#8
0
        public bool Send(string toEmail, string toName, string subject, string body)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(Config.DisplayName, Config.Username));
            message.To.Add(new MailboxAddress(toName, toEmail));
            message.Subject = subject;

            var bodyBuilder = new BodyBuilder();
            var newBody     = "<img src='https://vfr.beawre.com/Beawre_logo.png' style='width: 140px; height: 40px;' /><br/><br/>" + body;

            bodyBuilder.HtmlBody = newBody;

            message.Body = bodyBuilder.ToMessageBody();

            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;

                client.Connect(Config.Url, 587, false);

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(Config.Username, Config.Password);

                client.Send(message);
                client.Disconnect(true);
                return(true);
            }
        }
示例#9
0
        public IActionResult Mail()
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("bellroy", "*****@*****.**"));
            message.To.Add(new MailboxAddress("igna", "*****@*****.**"));
            message.Subject = "Invoice From Bellroy";
            var get  = from i in _AppDbContext.purchases.OrderBy(i => i.id) select i;
            var last = get.LastOrDefault();

            message.Body = new TextPart("plain")
            {
                Text = @"Hello " + last.nama +
                       "\nThanks for purchasing our best collection \n" +
                       "Here is your purchase details :\n" +
                       "Amount : Rp. " + last.totalPurchase
            };
            using (var emailClient = new MailKit.Net.Smtp.SmtpClient()) {
                emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                emailClient.Connect("smtp.mailtrap.io", 587, false);
                emailClient.Authenticate("31e443602f2a8a", "187ef92862e63c");
                emailClient.Send(message);
            }
            return(View("Success"));
        }
示例#10
0
    // Gửi email, theo nội dung trong mailContent
    public async Task SendMail(MailContent mailContent)
    {
        var email = new MimeMessage();

        email.Sender = MailboxAddress.Parse(mailSettings.Mail);
        email.To.Add(MailboxAddress.Parse(mailContent.To));
        email.Subject = mailContent.Subject;


        var builder = new BodyBuilder();

        builder.HtmlBody = mailContent.Body;
        email.Body       = builder.ToMessageBody();

        // dùng SmtpClient của MailKit
        using var smtp = new MailKit.Net.Smtp.SmtpClient();

        try {
            smtp.Connect(mailSettings.Host, mailSettings.Port, SecureSocketOptions.StartTls);
            smtp.Authenticate(mailSettings.Mail, mailSettings.Password);
            await smtp.SendAsync(email);
        }
        catch (Exception ex) {
            logger.LogInformation("Lỗi gửi mail");
            logger.LogError(ex.Message);
        }

        smtp.Disconnect(true);

        logger.LogInformation("send mail to " + mailContent.To);
    }
        public bool Send(string subject, string message, string senderEmail, string receiverEmail)
        {
            using (SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_emailConfiguration.Host, _emailConfiguration.Port, MailKit.Security.SecureSocketOptions.SslOnConnect);
                client.Authenticate(_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
                };

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

            return(true);
        }
示例#12
0
        public ActionResult SendEmail()
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("TheCodeBuzz", "*****@*****.**"));
                message.To.Add(new MailboxAddress("TheCodeBuzz", "*****@*****.**"));
                message.Subject = "My First Email";
                message.Body    = new TextPart("plain")
                {
                    Text = "Email is Working Fine"
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);

                    client.Authenticate("*****@*****.**", "password");
                    //SMTP server authentication if needed
                    // client.Authenticate("*****@*****.**", "xxxxx");

                    client.Send(message);

                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(StatusCode(500, "Error occured"));
            }

            return(Ok(true));
        }
示例#13
0
        public IActionResult Link(ShareViewModel vm)
        {
            var domain   = HttpContext.Request.Host.Value;     //localhos:1234
            var protocol = HttpContext.Request.Scheme + "://"; //https
            var url      = Url.RouteUrl("CarDetailsPage", new { make = vm.Brand, model = vm.Model, registrationNumber = vm.RegistrationNumber, id = vm.CarId });
            var FullUrl  = protocol + domain + url;

            var msg = new MimeMessage();

            msg.From.Add(new MailboxAddress("*****@*****.**"));
            msg.To.Add(new MailboxAddress(vm.Email));

            msg.Subject = "En vän delat bil från BolindersBil";
            msg.Body    = new TextPart("Html")
            {
                Text = "<strong>Kolla in denna schyssta bilen som finns i vårt lager</strong>" + "<br/>" + $"<a href='{FullUrl}' target='_blank'>{FullUrl}</a>",
                ContentTransferEncoding = ContentEncoding.QuotedPrintable
            };


            var client = new MailKit.Net.Smtp.SmtpClient();

            client.Connect("localhost", 25, false);
            client.Send(msg);
            client.Disconnect(true);


            var url2 = Url.RouteUrl("CarDetailsPage", new { make = vm.Brand, model = vm.Model, registrationNumber = vm.RegistrationNumber, id = vm.CarId });

            return(Redirect(url2));
        }
示例#14
0
 public IActionResult Mail(string inputName, string inputEmail, string inputMessage)
 {
     try
     {
         var message = new MimeMessage();
         message.From.Add(new MailboxAddress(inputEmail));
         message.To.Add(new MailboxAddress("*****@*****.**"));
         message.Subject = "Message from: " + inputName;
         message.Body    = new TextPart("plain")
         {
             Text = inputMessage
         };
         using (var client = new SmtpClient())
         {
             client.Connect("smtp.gmail.com", 587, true);
             client.Authenticate("*****@*****.**", "Tiger021");
             client.Send(message);
             client.Disconnect(true);
         };
         return(RedirectToAction("Index"));
     }
     catch (Exception exp)
     {
         ModelState.Clear();
         ViewBag.Message = $" We have a problem here {exp.Message}";
         return(RedirectToAction("Index"));
     }
 }
示例#15
0
		public static void PrintCapabilities ()
		{
			using (var client = new SmtpClient ()) {
				client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

				if (client.Capabilities.HasFlag (SmtpCapabilities.Authentication)) {
					var mechanisms = string.Join (", ", client.AuthenticationMechanisms);
					Console.WriteLine ("The SMTP server supports the following SASL mechanisms: {0}", mechanisms);

					// Note: if we don't want MailKit to use a particular SASL mechanism, we can disable it like this:
					client.AuthenticationMechanisms.Remove ("XOAUTH2");

					client.Authenticate ("username", "password");
				}

				if (client.Capabilities.HasFlag (SmtpCapabilities.Size))
					Console.WriteLine ("The SMTP server has a size restriction on messages: {0}.", client.MaxSize);

				if (client.Capabilities.HasFlag (SmtpCapabilities.Dsn))
					Console.WriteLine ("The SMTP server supports delivery-status notifications.");

				if (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime))
					Console.WriteLine ("The SMTP server supports Content-Transfer-Encoding: 8bit");

				if (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime))
					Console.WriteLine ("The SMTP server supports Content-Transfer-Encoding: binary");

				if (client.Capabilities.HasFlag (SmtpCapabilities.UTF8))
					Console.WriteLine ("The SMTP server supports UTF-8 in message headers.");

				client.Disconnect (true);
			}
		}
示例#16
0
        public static void Send(Order order, bool Add)
        {
            var message = new MimeMessage
            {
                Sender  = new MailboxAddress("Cinema - Pawel Dziwura (Comarch)", "*****@*****.**"),
                Subject = "Order confirmed"
            };

            if (Add)
            {
                message.Body = new TextPart(TextFormat.Plain)
                {
                    Text = "Hello " + order.OrderUser.Name + " \nYour order (" + order.OrderSeance.StartDate + ") has been confirmed."
                };
            }
            else
            {
                message.Body = new TextPart(TextFormat.Plain)
                {
                    Text = "Hello " + order.OrderUser.Name + " \nYour order (" + order.OrderSeance.StartDate + ") has been deleted."
                };
            }

            message.To.Add(new MailboxAddress("Client", "*****@*****.**"));

            using (var client = new SmtpClient())
            {
                client.SslProtocols = SslProtocols.Tls;
                client.Connect("smtp.comarch.com", 465);
                client.Authenticate("*****@*****.**", "type your password");
                client.Send(message);
            }
        }
示例#17
0
        public IActionResult Create(UserDetails userDetails)
        {
            if (ModelState.IsValid)
            {
                var    messsage = new MimeMessage();
                Random random   = new Random();
                String number   = random.Next(0, 999999).ToString("D6");

                messsage.From.Add(new MailboxAddress("Test Address", "*****@*****.**"));
                messsage.To.Add(new MailboxAddress("Test", "*****@*****.**"));
                messsage.Subject = "testmail";
                messsage.Body    = new TextPart("plain")
                {
                    //"Dear " + signUpModel.Email + ", <br /><br /> '" + number + "' is the password to Register  <br /><br /> Thanks & Regards, <br />Rashmi";

                    Text = "Dear " + userDetails.Name + ", <br /><br /> '" + number + "' is the password to Register  <br /><br /> Thanks & Regards, <br />Rashmi"
                };
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate("", "");
                    client.Send(messsage);
                    client.Disconnect(true);
                }
                return(RedirectToAction("about", "home"));
            }
            return(View());
        }
示例#18
0
        public async Task SendEmailAsync(MailRequest mailRequest)
        {
            var email = new MimeMessage();

            email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
            email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
            email.Subject = mailRequest.Subject;
            var builder = new BodyBuilder();

            if (mailRequest.Attachments != null)
            {
                byte[] fileBytes;
                foreach (var file in mailRequest.Attachments)
                {
                    if (file.Length > 0)
                    {
                        using (var ms = new MemoryStream())
                        {
                            file.CopyTo(ms);
                            fileBytes = ms.ToArray();
                        }
                        builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
                    }
                }
            }
            builder.HtmlBody = mailRequest.Body;
            email.Body       = builder.ToMessageBody();
            using var smtp   = new MailKit.Net.Smtp.SmtpClient();
            smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.SslOnConnect);
            smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
            await smtp.SendAsync(email);

            smtp.Disconnect(true);
        }
示例#19
0
        public IActionResult SendMail(string email, string messagecontent, string subject, string name)
        {
            if (email == null || messagecontent == null || subject == null || name == null)
            {
                ModelState.AddModelError("Hata", "Eksik Bilgi");
                return(View("ErrorPage"));
            }
            else
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("*****@*****.**"));
                message.To.Add(new MailboxAddress("*****@*****.**"));
                message.Subject = subject;
                message.Body    = new TextPart("html")
                {
                    Text = "BAŞLIK:" + subject + "<br>" +
                           name + " 'dan <br> " +
                           email + " 'dan <br> " +
                           " Mesaj : " + messagecontent
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    //587
                    client.Connect("srvm04.turhost.com", 587, false);
                    client.Authenticate("*****@*****.**", "Qwerty123");
                    client.Send(message);
                    client.Disconnect(true);
                };
                return(RedirectToAction("Index", "Home"));
            }
        }
示例#20
0
        public IActionResult Send(Purchase email)
        {
            var message      = new MimeMessage();
            var user         = (from i in _AppDbContext.purchases.OrderBy(x => x.id) select i).LastOrDefault();
            var nama         = user.firstName + " " + user.lastName;
            var emailAddress = user.email;
            var amount       = user.totalPrice;

            message.From.Add(new MailboxAddress("Essence", "*****@*****.**"));
            message.To.Add(new MailboxAddress(nama, emailAddress));
            message.Subject = "Your Purchase";
            message.Body    = new TextPart("Plain")
            {
                Text = @"Dear " + nama + "," + "\nThank You For Your Purchasing. \n" + "Your Total Amount is : Rp. " + amount
            };

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("smtp.mailtrap.io", 587, false);
                client.Authenticate("785fd04dea6d9c", "6057ae43ba12a4");
                client.Send(message);
                client.Disconnect(true);
            }
            return(RedirectToAction("Checkout", "Home"));
        }
示例#21
0
 public ActionResult <IEnumerable <bool> > SendEmail()
 {
     try
     {
         var message = new MimeMessage();
         message.From.Add(new MailboxAddress("HomeShopping", "*****@*****.**"));
         message.To.Add(new MailboxAddress("User", "*****@*****.**"));
         message.Subject = "My First Email";
         message.Body    = new TextPart("plain")
         {
             Text = "ABC"
         };
         using (var client = new MailKit.Net.Smtp.SmtpClient())
         {
             client.Connect("smtp.gmail.com", 587, false);
             client.Authenticate("*****@*****.**", "Minhman23199");
             client.Send(message);
             client.Disconnect(true);
             client.Dispose();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(StatusCode(500, "Error occured"));
     }
     return(Ok(true));
 }
示例#22
0
        public static void TestSendMailDemo()
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MailboxAddress("Joey Tribbiani", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "*****@*****.**"));
            message.Subject = "This is a Test Mail";
            var plain = new MimeKit.TextPart("plain")
            {
                Text = @"不好意思,我在测试程序,Sorry!"
            };

            // now create the multipart/mixed container to hold the message text and the
            // image attachment
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect("smtp.live.com", 587, 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
                var mailFromAccount = "*****@*****.**";
                var mailPassword    = "******";
                client.Authenticate(mailFromAccount, mailPassword);

                client.Send(message);
                client.Disconnect(true);
            }
        }
示例#23
0
        public void SendEmailAsync(SendModel sendModel)
        {
            var senderEmail    = "*****@*****.**";
            var senderPassword = "******";
            var senderSMTP     = "smtp.yandex.ru";

            var email = new MimeMessage
            {
                Body = new TextPart {
                    Text = sendModel.Body
                },
                Subject = sendModel.Subject,
            };

            email.From.Add(new MailboxAddress(senderEmail));
            email.To.Add(new MailboxAddress(sendModel.MailTo));

            MailMessage mail = new MailMessage
            {
                From = new MailAddress(senderEmail)         //адрес отправителя
            };                                              //создание экземпляра MailMessage

            mail.To.Add(new MailAddress(sendModel.MailTo)); //адрес получателя
            mail.Subject = sendModel.Subject;               //заголовок письма
            mail.Body    = sendModel.Body;                  //сам текст письма

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(senderSMTP, 465, true);
                client.Authenticate(senderEmail, senderPassword);
                client.Send(email);

                client.Disconnect(true);
            }
        }
示例#24
0
        public void Send(TaskReminder reminder)
        {
            var message = _translator.Translate(reminder);

            using (var client = new SmtpClient())
            {

                //_smtpDetails = new SmtpDetails()
                //{
                //    Server = "smtp.friends.com",
                //    Port = 587,
                //    UserName = "******",
                //    Password = "******"
                //};


                client.Connect(_smtpDetails.Server, _smtpDetails.Port, 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
                client.Authenticate(_smtpDetails.UserName, _smtpDetails.Password);

                client.Send(message);
                client.Disconnect(true);
            }
        }
示例#25
0
        private void Send(MimeMessage mailMessage)
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.None);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(_emailConfig.UserName, _emailConfig.Password);

                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    ErrMsg = ex.Message;
                    //log an error message or throw an exception or both.
                    //throw;
                }
                finally
                {
                    client.Disconnect(true);
                    client.Dispose();
                }
            }
        }
示例#26
0
        private void Send(MimeMessage mailMessage)
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    //client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.Auto);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(_emailConfig.UserName, _emailConfig.Password);

                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    client.Disconnect(true);
                    client.Dispose();
                }
            }
        }
示例#27
0
        public bool SendEmail(EmailModel model)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(model.Alias, model.FromEmail));
                message.To.Add(new MailboxAddress(model.ToName, model.ToEmail));
                message.Subject = model.Subject;
                message.Body    = new TextPart()
                {
                    Text = model.Message
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    // email

                    //SMTP server authentication if needed
                    client.Authenticate("*****@*****.**", "Harder01!");
                    client.Send(message);
                    client.Disconnect(true);
                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#28
0
        public static void FrontEnd(string[] args)
        {
            MainActivity = new MainActivity ();

            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("test", "*****@*****.**"));
            message.To.Add (new MailboxAddress (MainActivity.nome, MainActivity.email));
            message.Subject = "Obrigado por se candidatar";

            message.Body = new TextPart ("plain") {
                Text = @"Obrigado por se candidatar, assim que tivermos uma vaga disponível

            para programador Front-End entraremos em contato."

            };

            using (var client = new SmtpClient ()) {
                client.Connect ("smtp.test.com", 587, 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
                client.Authenticate ("test", "password");

                client.Send (message);
                client.Disconnect (true);
            }
        }
示例#29
0
        public async void Send(string toAddress, string subject, string body, bool sendAsync = true)
        {
            var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));

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

            mimeMessage.Subject = subject;

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = body
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_smtpServer, _smtpPort, _enableSsl);
                client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps
                if (sendAsync)
                {
                    await client.SendAsync(mimeMessage);
                }
                else
                {
                    client.Send(mimeMessage);
                }
                client.Disconnect(true);
            }
        }
示例#30
0
 /// <summary>
 /// MAIL KIT
 /// Info : http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/
 /// </summary>
 public static void SendEmail(string email, string name, string subject, string message,byte[] attachment = null,string attachmentName ="Facture")
 {
     var mimeMessage = new MimeMessage();
     mimeMessage.From.Add(new MailboxAddress(Configurations.Application.StolonsLabel, Configurations.Application.MailAddress));
     mimeMessage.To.Add(new MailboxAddress(name, email));
     mimeMessage.Subject = subject;
     var bodyBuilder = new BodyBuilder();
     if(attachment != null)
         bodyBuilder.Attachments.Add(attachmentName,attachment);
     bodyBuilder.HtmlBody = message;
     mimeMessage.Body = bodyBuilder.ToMessageBody();
     try
     {
         using (var client = new SmtpClient())
         {
             client.Connect(Configurations.Application.MailSmtp, Configurations.Application.MailPort, false);
             client.AuthenticationMechanisms.Remove("XOAUTH2");
             // Note: since we don't have an OAuth2 token, disable
             // the XOAUTH2 authentication mechanism.
             client.Authenticate(Configurations.Application.MailAddress, Configurations.Application.MailPassword);
             client.Send(mimeMessage);
             client.Disconnect(true);
         }
     }
     catch (Exception except)
     {
         Console.WriteLine("Error on sending mail : " + except.Message);
     }
 }
示例#31
0
        public ActionResult <IEnumerable <bool> > SendEmail([FromBody] string confirmationLink)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Alchematic", "*****@*****.**"));
                message.To.Add(new MailboxAddress("User", "*****@*****.**"));
                message.Subject = "Confirmation Link";
                message.Body    = new TextPart("plain")
                {
                    Text = confirmationLink
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);

                    //SMTP server authentication if needed
                    client.Authenticate("*****@*****.**", "xxxxx");

                    client.Send(message);

                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(StatusCode(500, "Error occured"));
            }

            return(Ok(true));
        }
示例#32
0
        public HttpStatusCode Connect(ProviderParams providerParams)
        {
            _imapClient = new ImapClient();
            _smtpClient = new MailKit.Net.Smtp.SmtpClient();
            _imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
            try
            {
                _imapClient.Connect(providerParams.ImapServerName, providerParams.ImapPortNumber, true);
                _smtpClient.Connect(providerParams.SmtpServerName, providerParams.SmtpPortNumber, true);
                _imapClient.AuthenticationMechanisms.Remove("XOAUTH2");
                _smtpClient.Authenticate(providerParams.EmailAddress, providerParams.Password);
                _imapClient.Authenticate(providerParams.EmailAddress, providerParams.Password);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
                return(HttpStatusCode.ExpectationFailed);
            }

            if (_imapClient.IsConnected && _smtpClient.IsConnected)
            {
                _currentFolder = "";
                return(HttpStatusCode.OK);
            }
            else
            {
                return(HttpStatusCode.InternalServerError);
            }
        }
示例#33
0
        public void BtnSubmit_Clicked(object sender, EventArgs e)
        {
            if (FormValidation()) //TODO: Remove comments
            {
                return;
            }

            #region WriteMessage
            string msg = "Jméno:" + editName.Text + Environment.NewLine +
                         "Příjmení:" + editName2.Text + Environment.NewLine +
                         "Email:" + editMail.Text + Environment.NewLine +
                         "Telefon:" + editPhone.Text + Environment.NewLine +
                         "Počet bodů:" + Visited;
            MailMessage message;
            try
            {
                message = new MailMessage()
                {
                    From    = new MailAddress("*****@*****.**"),
                    To      = { new MailAddress("*****@*****.**") },
                    Subject = "Tropic - Soutěž",
                    Body    = msg
                };
            }
            catch (Exception ex)
            {
                DisplayAlert("Chyba", ex.ToString(), "Ok");
                return;
            }

            #endregion

            #region SendEmail
            try
            {
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587);
                    client.SslProtocols = System.Security.Authentication.SslProtocols.Default;

                    client.Authenticate("*****@*****.**", "tropic213021");
                    client.Send((MimeMessage)message);
                    client.Disconnect(true);
                }

                Settings.FinishedEvents += Settings.CurrentEvent.Id.ToString() + ";";
                List <string> list = Settings.Stands.Split('.').ToList();
                list.RemoveAll(x => x.StartsWith(Settings.CurrentEvent.Id + "."));
                DisplayAlert("Posláno", "Jste úspěšně zaregistrováni do soutěže.", "Ok");
            }
            catch (Exception ex)
            {
                DisplayAlert("Chyba", ex.Message, "Ok");
                Crashes.TrackError(ex);
                return;
            }
            #endregion
        }
示例#34
0
        private static void SendMimeMessage(MimeMessage mail)
        {
            var client = new MailKit.Net.Smtp.SmtpClient();

            client.Connect(HostIP, HostPort, false);
            client.Authenticate(Username, Pass);
            client.Send(mail);
            client.Disconnect(true);
        }
示例#35
0
        public ActionResult EditEvent(Event events)
        {
            var CurrentUser = User.Identity.GetUserId();

            var FoundEvent = db.events.Where(e => e.EventId == events.EventId).SingleOrDefault();

            try
            {
                FoundEvent.EventName        = events.EventName;
                FoundEvent.EventDate        = events.EventDate;
                FoundEvent.Street           = events.Street;
                FoundEvent.City             = events.City;
                FoundEvent.State            = events.State;
                FoundEvent.Zip              = events.Zip;
                FoundEvent.TicketsAvailable = events.TicketsAvailable;
                FoundEvent.TicketPrice      = events.TicketPrice;
                db.SaveChanges();
                var          foundbookmarkers = db.bookmarks.Where(b => b.EventId == FoundEvent.EventId).ToList();
                List <Guest> foundGuest       = new List <Guest>();
                foreach (var item in foundbookmarkers)
                {
                    var guestFound = db.guests.Where(g => g.GuestId == item.GuestId).Single();
                    foundGuest.Add(guestFound);
                }

                foreach (Guest guest in foundGuest)
                {
                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress($"{FoundEvent.EventName}", "*****@*****.**"));
                    message.To.Add(new MailboxAddress($"{guest.FirstName}, {guest.LastName}", "*****@*****.**"));
                    message.Subject = "Event Update";

                    message.Body = new TextPart("plain")
                    {
                        Text = $@"Hello ,
                        We would like to notify you on our updates to our event.               
                        -- GroupCapStone"
                    };
                    using (var client = new MailKit.Net.Smtp.SmtpClient())
                    {
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                        client.Connect("smtp.gmail.com", 587, false);
                        client.Authenticate("sweepsstackproject", "sweep12!!");
                        client.Send(message);
                        client.Disconnect(true);
                    }
                }

                return(RedirectToAction("MyEvents"));
            }

            catch
            {
                return(RedirectToAction("MyEvents"));
            }
        }
        /// <summary>
        /// Occurs when the control is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void SendMailButton_Click(object sender, EventArgs e)
        {
            Int32.TryParse(imapPortTextBox.Text, out int port);
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(smtpUsernameTextBox.Text));
            message.To.Add(new MailboxAddress(users.ElementAt(GetIdOfSelectedUserInGrid()).MailAddress.Address));
            message.Subject = smtpSubjectTextBox.Text;
            message.Body    = new TextPart("plain")
            {
                Text = smtpMessageBodyTextBox.Text
            };

            try
            {
                using (MailKitSmtp.SmtpClient client = new MailKitSmtp.SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, err) => true;

                    if (smtpSslCheckBox.Enabled)
                    {
                        client.Connect(smtpHostTextBox.Text, port, true);
                    }
                    else if (smtpTlsCheckBox.Enabled)
                    {
                        client.Connect(smtpHostTextBox.Text, port, SecureSocketOptions.StartTlsWhenAvailable);
                    }
                    else
                    {
                        client.Connect(smtpHostTextBox.Text, port, SecureSocketOptions.Auto);
                    }

                    client.Authenticate(smtpUsernameTextBox.Text, smtpPasswordTextBox.Text);
                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to send message, please check the connection.", "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#37
0
		public static void SendMessage (MimeMessage message)
		{
			using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) {
				client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				client.Send (message);

				client.Disconnect (true);
			}
		}
示例#38
0
        public bool SendForgotPasswordResetLink(string path, AppUser appUser, AppUserAccessKey accessKey)
        {
            bool sucess = false;
            //From Address
            var FromAddress     = "*****@*****.**";
            var FromAdressTitle = "Camerack Studio";
            //To Address
            var toVendor = appUser.Email;
            //var toCustomer = email;
            var ToAdressTitle = "Camerack Studio";
            var Subject       = "Password Reset.";
            //var BodyContent = message;

            //Smtp Server
            var smtpServer = new AppConfig().EmailServer;
            //Smtp Port Number
            var smtpPortNumber = new AppConfig().Port;

            var mimeMessageVendor = new MimeMessage();

            mimeMessageVendor.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
            mimeMessageVendor.To.Add(new MailboxAddress(ToAdressTitle, toVendor));
            mimeMessageVendor.Subject = Subject;
            BodyBuilder bodyBuilder = new BodyBuilder();

            using (StreamReader data = File.OpenText(path))
            {
                if (data.BaseStream != null)
                {
                    //manage content

                    bodyBuilder.HtmlBody = data.ReadToEnd();
                    var body = bodyBuilder.HtmlBody;

                    var replace = body.Replace("NAME", appUser.Name);
                    replace = replace.Replace("DATE", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    replace = replace.Replace("URL", new AppConfig().MarketPlaceBaseUrl + "Account/ForgotPassword?accessCode=" + accessKey.PasswordAccessCode);
                    bodyBuilder.HtmlBody   = replace;
                    mimeMessageVendor.Body = bodyBuilder.ToMessageBody();
                }
            }
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(smtpServer, smtpPortNumber, true);
                // Note: only needed if the SMTP server requires authentication
                // Error 5.5.1 Authentication
                client.Authenticate(new AppConfig().Email, new AppConfig().Password);
                client.Send(mimeMessageVendor);
                sucess = true;
                client.Disconnect(true);
            }
            return(sucess);
        }
示例#39
0
        public async Task SendEmailAsync(History history)
        {
            var user = await _userService.GetUserAsync(history.CreatorId.ToString());

            var bonus = await _bonusService.FindBonusByIdAsync(history.BonusId);

            var vendor =
                await _vendorService.GetVendorByIdAsync(bonus.Company.Id);

            string promoCode = vendor.Name + RandomString(5);
            var    strToUser = String.Format("Hi {0} {1} your order recived. You ordered {2} by {3} company." +
                                             " For more information, please call {4} or email {5}." +
                                             " Validity period from {6} to {7}." +
                                             " Your promo code is {8}",
                                             user.FirstName, user.LastName,
                                             bonus.Title, bonus.Company.Name, bonus.Phone, vendor.Email, bonus.DateStart, bonus.DateEnd,
                                             promoCode);
            var strToVendor = String.Format("Dear {0},  {1} {2} will come to you with promo. PromoCode is {3}",
                                            vendor.Name, user.FirstName, user.LastName, promoCode);



            MimeMessage messageToUser = new MimeMessage();

            messageToUser.From.Add(new MailboxAddress(vendor.Name, vendor.Email));
            messageToUser.To.Add(new MailboxAddress(user.Email));
            messageToUser.Subject = "Get bonus";
            messageToUser.Body    = new BodyBuilder()
            {
                HtmlBody = String.Format("<div>{0}</div>", strToUser)
            }.ToMessageBody();


            MimeMessage messageToVendor = new MimeMessage();

            messageToVendor.From.Add(new MailboxAddress(user.FirstName, user.Email));
            messageToVendor.To.Add(new MailboxAddress(vendor.Email));
            messageToVendor.Subject = "Get bonus";
            messageToVendor.Body    = new BodyBuilder()
            {
                HtmlBody = String.Format("<div>{0}</div>", strToVendor)
            }.ToMessageBody();

            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_emailSettings.Value.SMTPServer, _emailSettings.Value.SMTPServerPort, true);
                client.Authenticate(_emailSettings.Value.EmailAddress, _emailSettings.Value.Password);
                client.Send(messageToUser);
                client.Send(messageToVendor);
                client.Disconnect(true);
            }
        }
示例#40
0
        /// <summary>
        /// Sends an email <paramref name="msg" />.
        /// </summary>
        /// <param name="msg">Message to send.</param>
        public void SendEmail(MimeMessage msg)
        {
            if (msg == null) {
                throw new ArgumentNullException(nameof(msg));
            };

            using (var client = new SmtpClient())
            {
                if (_options.UseSsl)
                {
                    client.Connect(_options.Server, _options.Port, SecureSocketOptions.StartTls);
                }
                else
                {
                    client.Connect(_options.Server, _options.Port, false);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                }

                client.Authenticate(_options.Username, _options.Password);
                client.Send(msg);
                client.Disconnect(true);
            }
        }
示例#41
0
        private void EnviarMensaje(MimeMessage mensaje)
        {
            using (var client = new SmtpClient())
            {
                client.Connect("smtp.sendgrid.net", 25, false);

                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate(
                    System.Environment.GetEnvironmentVariable("SENDGRID_USER"),
                    System.Environment.GetEnvironmentVariable("SENDGRID_PASS")
                    );

                client.Send(mensaje);
                client.Disconnect(true);
            }
        }
        public static SmtpClient CreateConnectedSmtpClient([NotNull] this ForwardRule forwardRule)
        {
            if (forwardRule == null) throw new ArgumentNullException(nameof(forwardRule));

            var client = new SmtpClient();

            client.Connect(forwardRule.SMTPServer, forwardRule.SMTPPort, forwardRule.SmtpUseSSL);

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

            if (!string.IsNullOrWhiteSpace(forwardRule.SMTPPassword)
                && !string.IsNullOrWhiteSpace(forwardRule.SMTPUsername))
            {
                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(forwardRule.SMTPUsername, forwardRule.SMTPPassword);
            }

            return client;
        }
示例#43
0
 public void SendEmail(MimeMessage emailMessage)
 {
     try
     {
         using (var client = new SmtpClient())
         {
             client.LocalDomain = PinoacresConstants.SMTPServerUrl;
             client.Connect(PinoacresConstants.SMTPServerUrl, 587, false);
             NetworkCredential networkCredential = new NetworkCredential() { UserName = PinoacresConstants.EmailFromAddress, Password = PinoacresConstants.EmailFromPassword };
             client.Authenticate(networkCredential);
             client.Send(emailMessage);
             client.Disconnect(true);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception Message");
         Console.WriteLine(ex.Message);
         throw;
     }
 }
示例#44
0
        public override void Execute()
        {
            if (!IsValidEmail(Invoice.Customer.Email))
                return;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("Anchorage Kid to Kid", "*****@*****.**"));
            message.To.Add(new MailboxAddress(Invoice.Customer.ToString(), Invoice.Customer.Email));
            message.Subject = "Receipt: " + Invoice.Id;

            var body = new BodyBuilder();
            body.HtmlBody = GetHtmlBody(Invoice);
            body.TextBody = "";
            message.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                var userName = SharedDb.PosimDb.GetString("SELECT StringValue FROM  DBA.BYR_PREFS where PrefTitle = 'emailUN'");
                var pw = SharedDb.PosimDb.GetString("SELECT StringValue FROM  DBA.BYR_PREFS where PrefTitle = 'emailPW'");
                var credentials = new NetworkCredential(userName, pw);

                // Note: if the server requires SSL-on-connect, use the "smtps" protocol instead
                var uri = new Uri("smtp://smtp.gmail.com:587");

                using (var cancel = new CancellationTokenSource())
                {
                    client.Connect(uri, cancel.Token);

                    // 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
                    client.Authenticate(credentials, cancel.Token);

                    client.Send(message, cancel.Token);
                    client.Disconnect(true, cancel.Token);
                }
            }
        }
示例#45
0
        public void SendNotification(IData data)
        {
            using (var client = new SmtpClient())
            {
                var smtpConfig = _config.Notification.Sender;

                client.Connect(smtpConfig.Server, smtpConfig.Port);
                client.Authenticate(smtpConfig.Username, smtpConfig.Password);

                var message = new MimeMessage();

                var mailboxAddresses = new List<MailboxAddress>();

                mailboxAddresses.Add(new MailboxAddress(data.Recipient, data.Recipient));

                message.From.Add(new MailboxAddress(smtpConfig.Username, smtpConfig.Username));
                message.To.AddRange(mailboxAddresses);
                message.Subject = data.Subject;
                message.Body = new TextPart("html") {Text = data.Body};

                client.Send(message);
            }
        }
示例#46
0
        public Task SendEmailAsync(string email, string subject, string message)
        {
            using (var client = new SmtpClient())
            {
                // client.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
               // client.Authenticate("username", "password");

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress("BodyReport", WebAppConfiguration.SmtpEmail));
                mimeMessage.To.Add(new MailboxAddress(email, email));
                mimeMessage.Subject = subject;
                mimeMessage.Body = new TextPart("html") { Text = message };

                client.Connect(WebAppConfiguration.SmtpServer, WebAppConfiguration.SmtpPort, SecureSocketOptions.None);
                client.Authenticate(WebAppConfiguration.SmtpUserName, WebAppConfiguration.SmtpPassword);

                client.Send(mimeMessage);
                client.Disconnect(true);
            }

            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
示例#47
0
        public Task SendEmailAsync(string server, string username, string password,
            string email, string subject, string message)
        {
            var mimeMessage = new MimeMessage();
            mimeMessage.From.Add(new MailboxAddress("Orlando Codecamp", username));
            mimeMessage.To.Add(new MailboxAddress(email,email));
            mimeMessage.Subject = subject;
            mimeMessage.Body = new TextPart("plain") { Text = message };

            using (var client = new SmtpClient())
            {
                client.Connect(server, 587, false);

                // We don't have an OAuth2 token, so we've disabled it
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                
                client.Authenticate(username, password);

                client.Send(mimeMessage);
                client.Disconnect(true);
            }
            
            return Task.FromResult(0);
        }
示例#48
0
        internal void SendMail(Contact contact)
        {
            MimeMessage message = new MimeMessage();
            message.Subject = $"Contact depuis le formulaire du site";
            message.Body = new TextPart { Text = $"Message envoyé par [{contact.Name}]\r\n mail saisi [{contact.Mail}] \r\n Message : \r\n {contact.Text}" };
            message.From.Add(new MailboxAddress("contact", this._smtpFrom));
            message.To.Add(new MailboxAddress("contact", this._smtpTo));

            using (var client = new SmtpClient())
            {
                client.Timeout = 3000;
                client.Connect(this._smtpAddress, this._smtpPort, SecureSocketOptions.SslOnConnect);

                // 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
                client.Authenticate(this._smtpUser, this._smtpPassword);

                client.Send(message);
                client.Disconnect(true);
            }
        }
        public void Send(MimeMessage message, string user, string pwd, string uri)
        {
            using (var client = new SmtpClient())
            {
                var credentials = new NetworkCredential(user, pwd);

                // Note: if the server requires SSL-on-connect, use the "smtps" protocol instead
                var uriObj = new Uri(uri);

                using (var cancel = new CancellationTokenSource())
                {
                    client.Connect(uriObj, cancel.Token);

                    // 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
                    client.Authenticate(credentials, cancel.Token);

                    client.Send(message, cancel.Token);
                    client.Disconnect(true, cancel.Token);
                }
            }
        }
示例#50
0
		public static void SendMessageWithOptions (MimeMessage message)
		{
			using (var client = new SmtpClient ()) {
				client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				var options = FormatOptions.Default.Clone ();

				if (client.Capabilities.HasFlag (SmtpCapabilities.UTF8))
					options.International = true;

				client.Send (options, message);

				client.Disconnect (true);
			}
		}
示例#51
0
        public JsonResult Compose(Email email)
        {
            JsonResult jsonResult = new JsonResult();
            string outputMessage = "";
            try
            {

                userGmailConfig = FetchUserGmailProfile();

                var message = new MimeMessage();

                message.From.Add(new MailboxAddress(email.FromEmail, email.FromEmail));

                if (email.ToAsCsv.Contains(','))
                {
                    foreach (var item in email.ToAsCsv.Split(','))
                    {
                        message.To.Add(new MailboxAddress(item, item));
                    }
                }
                else if (email.ToAsCsv.Contains(';'))
                {
                    foreach (var item in email.ToAsCsv.Split(';'))
                    {
                        message.To.Add(new MailboxAddress(item, item));
                    }
                }
                else
                {
                    message.To.Add(new MailboxAddress(email.ToAsCsv, email.ToAsCsv));
                }
                message.Subject = email.Subject;
                message.Body = new TextPart("plain")
                {
                    Text = email.Body
                };

                using (var client = new SmtpClient())
                {
                    try
                    {
                        client.Connect(userGmailConfig.OutgoingServerAddress, userGmailConfig.OutgoingServerPort);
                        client.Authenticate(new NetworkCredential(userGmailConfig.GmailUsername, userGmailConfig.GmailPassword));

                        client.Send(message);
                        client.Disconnect(true);

                        outputMessage = "Your message was sent successfully";
                    }
                    catch (Exception)
                    {
                        outputMessage = "There was an error sending your mail.";
                    }
                }
            }
            catch (Exception ex)
            {
                outputMessage = "There was an error in processing your request. Exception: " + ex.Message;
            }

            jsonResult.Data = new
            {
                message = outputMessage,
            };
            return jsonResult;
        }
示例#52
0
 private void SendEmail(MimeMessage message)
 {
     using (var client = new SmtpClient())
     {
         var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
         client.Connect(_config.Host, _config.Port, true, cts.Token);
         client.Authenticate(_config.Username, _config.Password, cts.Token);
         client.Send(message, cts.Token);
     }
 }
        /*
         * sends message
         */
        internal static void SendMessage(Node ip, Node dp, MimeMessage msg)
        {
            string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false);
            int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false);
            bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("implicit-ssl", "false"), dp, ip, false);
            string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false);
            string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false);

            using (SmtpClient client = new SmtpClient())
            {
                client.Connect(host, port, implicitSsl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                if (!string.IsNullOrEmpty(username))
                    client.Authenticate(username, password);
                client.Send(msg);
                client.Disconnect(true);
            }
        }
示例#54
0
		public static void SendMessage (MimeMessage message)
		{
			using (var client = new SmtpClient ()) {
				try {
					client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
				} catch (SmtpCommandException ex) {
					Console.WriteLine ("Error trying to connect: {0}", ex.Message);
					Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode);
					return;
				} catch (SmtpProtocolException ex) {
					Console.WriteLine ("Protocol error while trying to connect: {0}", ex.Message);
					return;
				}

				// Note: Not all SMTP servers support authentication, but GMail does.
				if (client.Capabilities.HasFlag (SmtpCapabilities.Authentication)) {
					try {
						client.Authenticate ("username", "password");
					} catch (AuthenticationException ex) {
						Console.WriteLine ("Invalid user name or password.");
						return;
					} catch (SmtpCommandException ex) {
						Console.WriteLine ("Error trying to authenticate: {0}", ex.Message);
						Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode);
						return;
					} catch (SmtpProtocolException ex) {
						Console.WriteLine ("Protocol error while trying to authenticate: {0}", ex.Message);
						return;
					}
				}

				try {
					client.Send (message);
				} catch (SmtpCommandException ex) {
					Console.WriteLine ("Error sending message: {0}", ex.Message);
					Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode);

					switch (ex.ErrorCode) {
					case SmtpErrorCode.RecipientNotAccepted:
						Console.WriteLine ("\tRecipient not accepted: {0}", ex.Mailbox);
						break;
					case SmtpErrorCode.SenderNotAccepted:
						Console.WriteLine ("\tSender not accepted: {0}", ex.Mailbox);
						break;
					case SmtpErrorCode.MessageNotAccepted:
						Console.WriteLine ("\tMessage not accepted.");
						break;
					}
				} catch (SmtpProtocolException ex) {
					Console.WriteLine ("Protocol error while sending message: {0}", ex.Message);
				}

				client.Disconnect (true);
			}
		}
示例#55
0
        public RC sendMessage(string sReceiverAddress, string sMessage, int iSmtpPort=587)
        {
            var message = new MimeMessage ();
            message.From.Add(new MailboxAddress(m_AuthInfo.m_sId, m_AuthInfo.m_sId));
            message.To.Add (new MailboxAddress (sReceiverAddress, sReceiverAddress));

            message.Subject = "";
            string sEncryptedMessage = "";

            //TODO: return error if mail cannot be send encrypted
            try
            {
                sEncryptedMessage = m_OpenPgpCrypter.encryptPgpString (sMessage, sReceiverAddress, true, false);
            }
            catch(Exception e) {
                m_Logger.log (ELogLevel.LVL_WARNING, e.Message, m_sModuleName);
            }

            message.Body = new TextPart ("plain") {
                Text = @sEncryptedMessage
            };

            using (var client = new SmtpClient ()) {
                client.Connect (m_EmailServiceDescription.SmtpUrl, iSmtpPort, true);

                // disable the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove ("XOAUTH2");

                client.Authenticate (m_AuthInfo.m_sId, m_AuthInfo.m_sPassword);

                client.Send (message);
                client.Disconnect (true);

                this.m_ConversationManager.addMessage (m_sProtocol, sMessage, m_AuthInfo.m_sId, sReceiverAddress);
            }

            return RC.RC_OK;
        }
示例#56
0
		public static void SendMessages (IList<MimeMessage> messages)
		{
			using (var client = new SmtpClient ()) {
				client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				foreach (var message in messages) {
					client.Send (message);
				}

				client.Disconnect (true);
			}
		}
示例#57
0
        public async Task SendAsync(string from,string from_name, string to,string cc, string subject, string messageBody, string host)
        {
            

            System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;

            var message = new MimeMessage();
            var e_from = new MailboxAddress(from, from_name);
            e_from.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
            
            message.From.Add(e_from);

            var e_to = new MailboxAddress("", to);
            e_to.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");

            message.To.Add(e_to);

            if (cc != null && cc != "" )
            {
                message.Cc.Add(new MailboxAddress("", cc));
            }

            message.Subject = subject;
          

            var builder = new BodyBuilder();

            //Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment
            //var app_environment = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Runtime.RuntimePath;//
            var app_environment = host;

            var filename = "http://"+ app_environment + "/templates/Mail/Signature.html";

            WebClient clients = new WebClient();
            
            string mailboy = clients.DownloadString(new Uri(filename));


            //var mailboy = System.IO.File.ReadAllText(filename);
            var image_source = new Uri("http://" + app_environment + "/images/M32G2.png");

            
            var image = builder.LinkedResources.Add("M32G2.png", clients.DownloadData(image_source)) ;
            
            image.ContentId = Path.GetFileName("M32G2.png");


            //imagepath= app_environment.ApplicationBasePath + 

            mailboy = mailboy.Replace("#imageLogo#", image.ContentId);
            mailboy = mailboy.Replace("#body#", messageBody);
            
            
            builder.HtmlBody = mailboy;
            //message.Body.ContentLocation = "pt-PT";
            //builder.HtmlBody = messageBody;



            //builder.HtmlBody = string.Format(@"<p>Hey!</p><img src=""cid:{0}"">", image.ContentId);
           
            message.Body = builder.ToMessageBody();
            
            using (var client = new SmtpClient())
            {
               client.Connect("smtp.gmail.com", 587, false);

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "Meridian321");
                
                client.Send(message);
                client.Disconnect(true);
            }
            

        }
示例#58
0
		public static void SendMessage (MimeMessage message)
		{
			using (var client = new SmtpClient ()) {
				// Note: since GMail requires SSL at connection time, use the "smtps"
				// protocol instead of "smtp".
				var uri = new Uri ("smtps://smtp.gmail.com:465");

				client.Connect (uri);

				client.Authenticate ("username", "password");

				client.Send (message);

				client.Disconnect (true);
			}
		}
        public IActionResult Submit(ContactForm form)
        {
            if (!ModelState.IsValid)
                return View("Index", form);

            var emailMessage = new MimeMessage();

            var address = new MailboxAddress(Settings.Title, Settings.EmailFromAndTo);
            emailMessage.From.Add(address);
            emailMessage.To.Add(address);
            emailMessage.Subject = Settings.EmailSubject;
            var message = "Name: " + form.Name + Environment.NewLine
                + "Company: " + form.Company + Environment.NewLine
                + form.PreferredMethod + ": " + form.Email + form.Phone + Environment.NewLine
                + "Message:" + Environment.NewLine
                + form.Message;
            emailMessage.Body = new TextPart("plain") { Text = message };

            using (var client = new SmtpClient())
            {
                client.Connect(Settings.EmailServer, 465);
                client.Authenticate(Settings.EmailUser, Cache.Config["EmailPassword"]);
                client.Send(emailMessage);
                client.Disconnect(true);
            }
            return View("Thanks");
        }
		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"));
			}
		}