当前位置: 首页>>代码示例>>C#>>正文


C# Mail.SmtpClient类代码示例

本文整理汇总了C#中System.Net.Mail.SmtpClient的典型用法代码示例。如果您正苦于以下问题:C# SmtpClient类的具体用法?C# SmtpClient怎么用?C# SmtpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SmtpClient类属于System.Net.Mail命名空间,在下文中一共展示了SmtpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendEmail

        /// <summary>
        /// Send Gmail Email Using Specified Gmail Account
        /// </summary>
        /// <param name="address">Receipients Adresses</param>
        /// <param name="subject">Email Subject</param>
        /// <param name="message">Enail Body</param>
        /// <param name="AttachmentLocations">List of File locations, null if no Attachments</param>
        /// <param name="yourEmailAdress">Gmail Login Adress</param>
        /// <param name="yourPassword">Gmail Login Password</param>
        /// <param name="yourName">Display Name that Receipient Will See</param>
        /// <param name="IsBodyHTML">Is Message Body HTML</param>
        public static void SendEmail(List<string> addresses, string subject, string message, List<string> AttachmentLocations, string yourEmailAdress, string yourPassword, string yourName, bool IsBodyHTML)
        {
            try
            {
                string email = yourEmailAdress;
                string password = yourPassword;

                var loginInfo = new NetworkCredential(email, password);
                var msg = new MailMessage();
                var smtpClient = new SmtpClient("smtp.gmail.com", 587);


                msg.From = new MailAddress(email, yourName);
                foreach (string address in addresses)
                {
                    msg.To.Add(new MailAddress(address));
                }
                msg.Subject = subject;
                msg.Body = message;
                msg.IsBodyHtml = IsBodyHTML;
                if (AttachmentLocations != null)
                {
                    foreach (string attachment in AttachmentLocations)
                    {
                        msg.Attachments.Add(new Attachment(attachment));
                    }
                }
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = loginInfo;
                smtpClient.Send(msg);

            }
            catch { }
        }
开发者ID:sanyaade-fintechnology,项目名称:NinjaTrader,代码行数:46,代码来源:Gmail.cs

示例2: sendMessage

 private void sendMessage()
 {
     MailAddress adresa = new MailAddress("[email protected]");
     MailMessage zpráva;
     if (logFile)
     {
         string log;
         using (StreamReader reader = new StreamReader(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Info", "Log", "logStatusBaru.log")))
         {
             log = reader.ReadToEnd();
         }
         if (log.Length > 50000)
             log.Remove(50000);
         zpráva = new MailMessage("[email protected]", "[email protected]", předmětTextBox.Text, textZprávyTextBox.Text + log);
     }
     else
     {
         zpráva = new MailMessage("[email protected]", "[email protected]", předmětTextBox.Text, textZprávyTextBox.Text);
     }
     SmtpClient klient = new SmtpClient();
     klient.Host = "smtp.gmail.com";
     klient.Port = 465;
     klient.EnableSsl = true;
     //klient.Send(zpráva);
 }
开发者ID:Cendrb,项目名称:UTU,代码行数:25,代码来源:OdeslatNázor.xaml.cs

示例3: Send

        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="to">The list of recipients</param>
        /// <param name="subject">The subject of the email</param>
        /// <param name="body">The body of the email, which may contain HTML</param>
        /// <param name="htmlEmail">Should the email be flagged as "html"?</param>
        /// <param name="cc">A list of CC recipients</param>
        /// <param name="bcc">A list of BCC recipients</param>
        public static void Send(List<String> to, String subject, String body, bool htmlEmail = false, List<String> cc = null, List<String> bcc = null)
        {
            // Need to have at least one address
            if (to == null && cc == null && bcc == null)
                throw new System.ArgumentNullException("At least one of the address parameters (to, cc and bcc) must be non-null");

            NetworkCredential credentials = new NetworkCredential(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.AdminEmail), JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPassword));
            // Set up the built-in MailMessage
            MailMessage mm = new MailMessage();
            mm.From = new MailAddress(credentials.UserName, "Just Press Play");
            if (to != null) foreach (String addr in to) mm.To.Add(new MailAddress(addr, "Test"));
            if (cc != null) foreach (String addr in cc) mm.CC.Add(new MailAddress(addr));
            if (bcc != null) foreach (String addr in bcc) mm.Bcc.Add(new MailAddress(addr));
            mm.Subject = subject;
            mm.IsBodyHtml = htmlEmail;
            mm.Body = body;
            mm.Priority = MailPriority.Normal;

            // Set up the server communication
            SmtpClient client = new SmtpClient
                {
                    Host = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPServer),
                    Port = int.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPort)),
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = credentials
                };

            client.Send(mm);
        }
开发者ID:RIT-MAGIC,项目名称:JustPressPlay,代码行数:40,代码来源:Email.cs

示例4: SendMessage

        public static void SendMessage(SmtpServer server, string from, string to, string subject, string content)
        {
            // compress Foe message and convert the compressed data to Base64 string
            byte[] compressedData = Foe.Common.CompressionManager.Compress(Encoding.UTF8.GetBytes(content));
            string based64 = Convert.ToBase64String(compressedData);

            // send email
            try
            {
                // create mail
                MailMessage mail = new MailMessage(from, to, subject, based64);

                // connect and send
                SmtpClient smtp = new SmtpClient(server.ServerName, server.Port);
                if (server.AuthRequired)
                {
                    smtp.EnableSsl = server.SslEnabled;
                    smtp.UseDefaultCredentials = false;
                    NetworkCredential cred = new NetworkCredential(server.UserName, server.Password);
                    smtp.Credentials = cred;
                }
                smtp.Send(mail);
            }
            catch (Exception except)
            {
                throw except;
            }
        }
开发者ID:gcode-mirror,项目名称:foe-project,代码行数:28,代码来源:MessageManager.cs

示例5: Send_with_Auth_Success_Test

        public void Send_with_Auth_Success_Test()
        {
            using (var server = new SmtpServerForUnitTest(
                address: IPAddress.Loopback,
                port: 2525,
                credentials: new[] { new NetworkCredential("[email protected]", "[email protected]$$w0rd") }))
            {
                server.Start();

                var client = new SmtpClient("localhost", 2525);
                client.Credentials = new NetworkCredential("[email protected]", "[email protected]$$w0rd");
                client.Send(
                    "[email protected]",
                    "[email protected],[email protected]",
                    "[HELLO WORLD]",
                    "Hello, World.");

                server.ReceivedMessages.Count().Is(1);
                var msg = server.ReceivedMessages.Single();
                msg.MailFrom.Is("<[email protected]>");
                msg.RcptTo.OrderBy(_ => _).Is("<[email protected]>", "<[email protected]>");
                msg.From.Address.Is("[email protected]");
                msg.To.Select(_ => _.Address).OrderBy(_ => _).Is("[email protected]", "[email protected]");
                msg.CC.Count().Is(0);
                msg.Subject.Is("[HELLO WORLD]");
                msg.Body.Is("Hello, World.");
            }
        }
开发者ID:jsakamoto,项目名称:smtp-server-4unittest,代码行数:28,代码来源:SmtpServerForUnitTestTest.cs

示例6: SendMail

 /// <summary>
 /// Sends an email
 /// </summary>
 /// <param name="Message">The body of the message</param>
 public void SendMail(string Message)
 {
     try
     {
         System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
         char[] Splitter = { ',' };
         string[] AddressCollection = to.Split(Splitter);
         for (int x = 0; x < AddressCollection.Length; ++x)
         {
             message.To.Add(AddressCollection[x]);
         }
         message.Subject = subject;
         message.From = new System.Net.Mail.MailAddress((from));
         message.Body = Message;
         message.Priority = Priority_;
         message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
         message.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
         message.IsBodyHtml = true;
         if (Attachment_ != null)
         {
             message.Attachments.Add(Attachment_);
         }
         System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Server,Port);
         if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
         {
             smtp.Credentials = new System.Net.NetworkCredential(UserName,Password);
         }
         smtp.Send(message);
         message.Dispose();
     }
     catch (Exception e)
     {
         throw new Exception(e.ToString());
     }
 }
开发者ID:summer-breeze,项目名称:ChengGouHui,代码行数:39,代码来源:EmailSender.cs

示例7: Enviar

        protected void Enviar(object sender, EventArgs e)
        {
            MailMessage email = new MailMessage();
            MailAddress de = new MailAddress(txtEmail.Text);

            email.To.Add("[email protected]");
            email.To.Add("[email protected]");
            email.To.Add("[email protected]");
            email.To.Add("[email protected]");
            email.To.Add("[email protected]");
            email.To.Add("[email protected]");

            email.From = de;
            email.Priority = MailPriority.Normal;
            email.IsBodyHtml = false;
            email.Subject = "Sua Jogada: " + txtAssunto.Text;
            email.Body = "Endereço IP: " + Request.UserHostAddress + "\n\nNome: " + txtNome.Text + "\nEmail: " + txtEmail.Text + "\nMensagem: " + txtMsg.Text;

            SmtpClient enviar = new SmtpClient();

            enviar.Host = "smtp.live.com";
            enviar.Credentials = new NetworkCredential("[email protected]", "");
            enviar.EnableSsl = true;
            enviar.Send(email);
            email.Dispose();

            Limpar();

            ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "alert('Email enviado com sucesso!');", true);
        }
开发者ID:JulianRSena,项目名称:projeto-suajogada,代码行数:30,代码来源:Contato.aspx.cs

示例8: SendMail

        public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "", string Password = "")
        {
            string response = "";
            try
            {
                using (SmtpClient smtp = new SmtpClient())
                {
                    MailMessage mail = new MailMessage();
                    mail.To.Add(to);
                    mail.From = new MailAddress(UserName);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.UseDefaultCredentials = false;
                    smtp.EnableSsl = true;
                    smtp.Host = "smtp.zoho.com";
                    smtp.Port = 587;
                    smtp.Credentials = new NetworkCredential(UserName, Password);
                    smtp.Send(mail);
                    response = "Success";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Message);
            }

            return response;
        }
开发者ID:socioboard,项目名称:socioboard-core,代码行数:31,代码来源:MailSenderZoho.cs

示例9: sendEmail

        public static void sendEmail(string emailFrom, string password, string emailTo, string subject, string body)
        {
            string smtpAddress = "smtp.gmail.com";
            int portNumber = 587;
            bool enableSSL = true;

            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFrom); //email của mình
                mail.To.Add(emailTo); //gửi tới ai
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;

                // Can set to false, if you are sending pure text.

                //mail.Attachments.Add(new Attachment("H:\\cpaior2012_path.pdf"));

                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFrom, password);
                    smtp.EnableSsl = enableSSL;
                    smtp.Send(mail);
                }
            }
        }
开发者ID:anhphamkstn,项目名称:DVMC,代码行数:26,代码来源:Mail.cs

示例10: SendEmail

        public static void SendEmail(string email, string subject, string body)
        {
            string fromAddress = ConfigurationManager.AppSettings["FromAddress"];
            string fromPwd = ConfigurationManager.AppSettings["FromPassword"];
            string fromDisplayName = ConfigurationManager.AppSettings["FromDisplayNameA"];
            //string cc = ConfigurationManager.AppSettings["CC"];
            //string bcc = ConfigurationManager.AppSettings["BCC"];

            MailMessage oEmail = new MailMessage
            {
                From = new MailAddress(fromAddress, fromDisplayName),
                Subject = subject,
                IsBodyHtml = true,
                Body = body,
                Priority = MailPriority.High
            };
            oEmail.To.Add(email);
            string smtpServer = ConfigurationManager.AppSettings["SMTPServer"];
            string smtpPort = ConfigurationManager.AppSettings["SMTPPort"];
            string enableSsl = ConfigurationManager.AppSettings["EnableSSL"];
            SmtpClient client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort))
            {
                EnableSsl = enableSsl == "1",
                Credentials = new NetworkCredential(fromAddress, fromPwd)
            };

            client.Send(oEmail);
        }
开发者ID:innoist,项目名称:Inventory-POS-IST,代码行数:28,代码来源:Utility.cs

示例11: SendMail

 /// <summary>
 /// Envia un correo por medio de un servidor SMTP
 /// </summary>
 /// <param name="from">correo remitente</param>
 /// <param name="fromPwd">contraseña del correo del remitente</param>
 /// <param name="userTo">usuario que solicito la recuperación de la contraseña</param>
 /// <param name="subject">encabezado del correo</param>
 /// <param name="smtpClient">sercidor smtp</param>
 /// <param name="port">puerto del servidor smtp</param>
 /// <returns>respuesta del envio</returns>
 public string SendMail(string from, string fromPwd, string userTo, string subject, string smtpClient, int port)
 {
     currentUser = userTo;
     userTo = GetCorreoUsuario(currentUser);
     if (userTo.Equals(string.Empty))
         return "El usuario no esta registrado.";
     else if (!InsertPassword(currentUser))
         return "No se ha podido crear una nueva contraseña. Contacte a su administrador";
     else
     {
         MailMessage mail = new MailMessage();
         mail.From = new MailAddress(from);
         mail.To.Add(userTo);
         mail.Subject = subject;
         mail.IsBodyHtml = true;
         mail.Body = GetMsg(from, currentUser);
         SmtpClient smtp = new SmtpClient(smtpClient);
         smtp.Credentials = new System.Net.NetworkCredential(from, fromPwd);
         smtp.Port = port;
         try
         {
             smtp.Send(mail);
             return "Se ha enviado su nueva contraseña. Revise su correo y vuelva a intentarlo";
         }
         catch (Exception ex)
         {
             return "No se ha podido completar la solicitud: " + ex.Message;
         }
     }   
 }
开发者ID:jibarradelgado,项目名称:medicuri,代码行数:40,代码来源:BlRecuperarContraseña.cs

示例12: SendEmailThroughGmail

        /// <summary>
        /// 使用Gmail发送邮件
        /// </summary>
        /// <param name="gmailAccount">Gmail账号</param>
        /// <param name="gmailPassword">Gmail密码</param>
        /// <param name="to">接收人邮件地址</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="attachPath">附件</param>
        /// <returns>是否发送成功</returns>
        public static bool SendEmailThroughGmail(String gmailAccount, String gmailPassword, String to, String subject, String body,
            String attachPath)
        {
            try
            {
                SmtpClient client = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(gmailAccount, gmailPassword),
                    Timeout = 20000
                };

                using (MailMessage mail = new MailMessage(gmailAccount, to) { Subject = subject, Body = body })
                {
                    mail.IsBodyHtml = true;

                    if (!string.IsNullOrEmpty(attachPath))
                    {
                        mail.Attachments.Add(new Attachment(attachPath));
                    }

                    client.Send(mail);
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
开发者ID:dalinhuang,项目名称:jxt-zhichengxinda,代码行数:45,代码来源:EmailUtility.cs

示例13: send_email_alert

        public void send_email_alert(string alert_message)
        {


          
            var fromAddress = new MailAddress("[email protected]", "Selenium Alert");
            var toAddress = new MailAddress("[email protected]", "Max");
            const string fromPassword = "098AZQ102030";
            const string subject = "Selenium Alert";
            

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = alert_message
            })
            {
                smtp.Send(message);
            }
        }
开发者ID:maxunger,项目名称:driv_t,代码行数:29,代码来源:EmailAlert.cs

示例14: Application_Error

        void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            if (httpException != null)
            {
                //switch (httpException.GetHttpCode())
                //{
                //    case 404:
                //        HttpContext.Current.Session["Message"] = "Страница не найдена!";
                //        break;
                //    case 500:
                //        //action = "Error";
                //        break;
                //    default:
                //        // action = "Error";
                //        HttpContext.Current.Session["Message"] = "Неизвестная ошибка. Попробуйте повторить действие позже.";
                //        break;
                //}
            }
            else
                HttpContext.Current.Session["Message"] = exception.Message;

            var message = new MailMessage();
            message.To.Add(new MailAddress("[email protected]"));
            message.Subject = "psub.net error";
            message.Body = exception.Message;
            message.IsBodyHtml = true;
            var client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network };
            client.Send(message);

            Response.Redirect(@"~/Exception/Error");
        }
开发者ID:pashaiva,项目名称:psub.Web,代码行数:33,代码来源:Global.asax.cs

示例15: SendContactEmail

        // email from contact form
        public void SendContactEmail(Registrant registrant)
        {
            emailBody += "NAME: " + registrant.FirstName + " " + registrant.LastName;
            emailBody += "<br><br>";
            emailBody += "EMAIL: " + registrant.Email;
            emailBody += "<br><br>";
            emailBody += "ZIP: " + registrant.ZipCode;
            emailBody += "<br><br>";
            emailBody += "COMMENTS:";
            emailBody += "<br><br>";
            emailBody += registrant.Comments;

            var message = new MailMessage(SMTPAddress, contactAddress)
            {
                Subject = "Contact Inquiry from Website",
                IsBodyHtml = true,
                Body = emailBody
            };

            var mailer = new SmtpClient();
            mailer.Host = SMTPHost;
            mailer.Credentials = new System.Net.NetworkCredential(SMTPAddress, SMTPPassword);
            mailer.Send(message);

            return;
        }
开发者ID:soularise,项目名称:NEST-MASTER,代码行数:27,代码来源:MailHandler.cs


注:本文中的System.Net.Mail.SmtpClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。