An SMTP client that can be used to send email messages.

The SmtpClient class supports both the "smtp" and "smtps" protocols. The "smtp" protocol makes a clear-text connection to the SMTP server and does not use SSL or TLS unless the SMTP server supports the STARTTLS extension. The "smtps" protocol, however, connects to the SMTP server using an SSL-wrapped connection.

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.

Inheritance: MailTransport
Esempio n. 1
10
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

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

                await client.SendAsync(emailMessage);
                await client.DisconnectAsync(true);
                //  }
            }
            catch (Exception ex) //todo add another try to send email
            {
                var e = ex;
                throw;
            }
           
        }
Esempio n. 2
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);
            }
        }
Esempio n. 3
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;
     }
 }
Esempio n. 4
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);
            }
        }
        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;
            }
        }
Esempio n. 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());
        }
Esempio n. 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);
            }
        }
Esempio n. 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"));
        }
Esempio n. 10
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));
        }
Esempio n. 11
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);
            }
        }
        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");
            }
        }
Esempio n. 13
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();
                }
            }
        }
Esempio n. 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);
        }
Esempio n. 15
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();
                }
            }
        }
Esempio n. 16
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);
            }
        }
Esempio n. 17
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);
            }
        }
Esempio n. 18
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);
            }
        }
Esempio n. 19
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());
        }
Esempio n. 20
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"));
     }
 }
Esempio n. 21
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"));
        }
        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"));
        }
Esempio n. 23
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"));
            }
        }
Esempio n. 24
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;
            }
        }
Esempio n. 25
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);
            }
        }
Esempio n. 26
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);
            }
        }
Esempio n. 27
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);
			}
		}
Esempio n. 28
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);
            }
        }
Esempio n. 29
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);
            }
        }
Esempio n. 30
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);
        }
Esempio n. 31
0
        private async Task SendAsync(MimeMessage mailMessage)
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    //client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.Auto);

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

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

                    client.Dispose();
                }
            }
        }
Esempio n. 32
0
        public static async Task SendEmailAsync(string email, string subject, string message)
        {
            Program.MedialynxData.historyDBAPI.Add(
                new HistoryItem(
                    "unknown",
                    "unknown",
                    "Mailing Service",
                    "SendEmailAsync called for: " + email
                    )
                );


            var emailMessage = new MimeMessage();

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

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

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

                await client.SendAsync(emailMessage);

                await client.DisconnectAsync(true);
            }
        }
Esempio n. 33
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);
     }
 }
Esempio n. 34
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));
        }
        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)
            {
            }
        }
Esempio n. 36
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();
                }
            }
        }
Esempio n. 37
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);
            }
        }
Esempio n. 38
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);
            }
        }
Esempio n. 39
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));
        }
 /// <summary>
 /// Sets up the smtp server and the mail message
 /// </summary>
 public void init()
 {
     _smtp = new SmtpClient();
     _builder = new BodyBuilder();
     _message = null; // will be filled in with Hy's email
     _subject = "Busted - It's Up to You Invitation";
     _destinations = new List<String>();
 }
Esempio n. 41
0
        public void TestBasicFunctionality()
        {
            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", "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 ()) {
                try {
                    client.ReplayConnect ("localhost", new SmtpReplayStream (commands), CancellationToken.None);
                } 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 {
                    var credentials = new NetworkCredential ("username", "password");
                    client.Authenticate (credentials, CancellationToken.None);
                } catch (Exception ex) {
                    Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
                }

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

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

                Assert.IsFalse (client.IsConnected, "Failed to disconnect");
            }
        }
Esempio n. 42
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);
			}
		}
Esempio n. 43
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);
            }
        }
Esempio n. 44
0
        public async Task Setup()
        {
            try
            {
                if (_setupInProgress) return;
                await _setupSemaphore.WaitAsync(Util.GetCancellationToken(10000));
                _setupInProgress = true;

                if (_timer != null)
                {
                    _timer.Enabled = false;
                    _timer.Elapsed -= _timer_Elapsed;
                    _timer.Dispose();
                }

                _timer = new Timer();
                _timer.Interval = 1000 * 60 * 2; //2 minutes
                _timer.Elapsed += _timer_Elapsed;
                _timer.AutoReset = false;
                _timer.Start();

                SmtpClient oldClient = null;

                if (_smtpClient != null)
                {
                    _smtpClient.Disconnected -= SmtpClientOnDisconnected;
                    oldClient = _smtpClient;
                }

                _smtpClient = await _factory.GetSmtpClient();

                oldClient?.Dispose();

                _smtpClient.Disconnected += SmtpClientOnDisconnected;

                Trace.WriteLine($"{_factory.MailBoxName}: SMTP Client Setup");

                _setupSemaphore.Release();
                _setupInProgress = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"{_factory.MailBoxName}:{ex.Message}");
            }
            
        }
        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;
        }
Esempio n. 46
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;
     }
 }
Esempio n. 47
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);
                }
            }
        }
Esempio n. 48
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);
            }
        }
Esempio n. 49
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);
        }
Esempio n. 50
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);
            }
        }
Esempio n. 51
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);
            }
        }
Esempio n. 52
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);
        }
Esempio n. 53
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);
            }

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

			using (var client = new SmtpClient ()) {
				try {
					client.ReplayConnect ("localhost", new SmtpReplayStream (commands), CancellationToken.None);
				} 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 {
					client.Send (CreateSimpleMessage (), CancellationToken.None);
					Assert.Fail ("Expected an ServiceNotAuthenticatedException");
				} catch (ServiceNotAuthenticatedException) {
					// this is the expected exception
				} catch (Exception ex) {
					Assert.Fail ("Did not expect this exception in Send: {0}", ex);
				}

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

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

				Assert.IsFalse (client.IsConnected, "Failed to disconnect");
			}
		}
Esempio n. 55
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;
        }
Esempio n. 56
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 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);
                }
            }
        }
Esempio n. 58
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 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");
        }
Esempio n. 60
-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);	
			}
		}