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


C# SmtpClient.SendMail方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            // Set sender email address, please change it to yours
            oMail.From = "[email protected]";

            // Set recipient email address, please change it to yours
            oMail.To = "[email protected]";

            // Set email subject
            oMail.Subject = "direct email sent from c# project";

            // Set email body
            oMail.TextBody = "this is a test email sent from c# project directly";

            // Set SMTP server address to "".
            SmtpServer oServer = new SmtpServer("");

            // Do not set user authentication
            // Do not set SSL connection

            try
            {
                Console.WriteLine("start to send email directly ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
开发者ID:arvind-web-developer,项目名称:csharp-projects-EASendMail,代码行数:35,代码来源:Program.cs

示例2: Form2_Load

        private void Form2_Load(object sender, EventArgs e)
        {
            byte[] ascii = Encoding.ASCII.GetBytes(textBox1.Text);

            foreach (Byte b in ascii)
            {
                if ((int)(b - 32) == 65 || (int)(b - 32) == 69 || (int)(b - 32) == 73 ||
                    (int)(b - 32) == 79 || (int)(b - 32) == 85)
                {

                    SmtpMail oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();

                    oMail.From = "[email protected]";
                    oMail.To = "[email protected]";
                    oMail.Subject = "Order Placed";
                    oMail.TextBody = "Good day \r\n \r\n" +
                                     "We would like to place an order for the following items. \r\n \r\n" +
                                     "Shampoo: 5 \r\n \r\n" +
                                     "Hair Dye: 7 \r\n \r\n" +
                                     "Regards \r\n" +
                                     "eSalon \r\n";

                    SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                    oServer.User = "[email protected]";
                    oServer.Password = "Ellemd33n";
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    oServer.Port = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    try
                    {
                        progressBar1.Visible = true;
                        textBox1.Visible = false;

                        progressBar1.Value = 0;
                        progressBar1.Step = 1;

                        for (int k = 0; k <= 100; k++)
                        {
                            progressBar1.PerformStep();
                        }

                        oSmtp.SendMail(oServer, oMail);
                        MessageBox.Show("Email was sent successfully!");

                        progressBar1.Visible = false;
                        textBox1.Visible = true;
                    }
                    catch (Exception ep)
                    {
                        MessageBox.Show("Failed to send email with the following error: ");
                        MessageBox.Show(ep.Message);
                    }
                }
            }

            textBox1.Clear();
            textBox1.Focus();
        }
开发者ID:DirkViljoen,项目名称:eSalon,代码行数:60,代码来源:Form2.cs

示例3: Sender

        public void Sender(String msg, String subject, String attachmentFileName, String email)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
            Debug.WriteLine(msg);
            //
            // Your Hotmail email address
            //oMail.From = "[email protected]";
            oMail.From = "[email protected]";
            // Set recipient email address
            oMail.To = email;

            // Set email subject
            oMail.Subject = subject;

            // Set email body
            oMail.TextBody = msg;

            if (!string.IsNullOrEmpty(attachmentFileName))
                oMail.AddAttachment(attachmentFileName);

            // Hotmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.live.com");
            // Hotmail user authentication should use your
            // email address as the user name.
            oServer.User = "[email protected]";
            oServer.Password = "6440mark";

            // detect SSL/TLS connection automatically
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            //oServer.ConnectType = SmtpConnectType.ConnectNormal;

            try
            {
                Debug.WriteLine("start to send email over SSL...");
                oSmtp.SendMail(oServer, oMail);
                Debug.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Debug.WriteLine("failed to send email with the following error:");
                Debug.WriteLine(ep.Message);
            }
            Debug.WriteLine(msg);
        }
开发者ID:samuelbritt,项目名称:6440-hit,代码行数:45,代码来源:HotmailEmail.cs

示例4: _DirectSend

        private void _DirectSend( ref SmtpMail oMail, ref SmtpClient oSmtp )
        {
            AddressCollection recipients = oMail.Recipients.Copy();
            int count = recipients.Count;
            for( int i = 0; i < count; i++ )
            {
                string err = "";
                MailAddress address = recipients[i] as MailAddress;

                bool terminated = false;
                try
                {
                    oMail.To.Clear();
                    oMail.Cc.Clear();
                    oMail.Bcc.Clear();

                    oMail.To.Add( address );
                    SmtpServer oServer = new SmtpServer( "" );

                    sbStatus.Text = String.Format( "Connecting server for {0} ... ", address.Address );
                    pgSending.Value = 0;
                    oSmtp.SendMail( oServer, oMail );
                    MessageBox.Show( String.Format( "The message to <{0}> was sent to {1} successfully!",
                        address.Address,
                        oSmtp.CurrentSmtpServer.Server ));

                    sbStatus.Text = "Completed";

                }
                catch( SmtpTerminatedException exp )
                {
                    err = exp.Message;
                    terminated = true;
                }
                catch( SmtpServerException exp )
                {
                    err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
                }
                catch( System.Net.Sockets.SocketException exp )
                {
                    err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
                }
                catch( System.ComponentModel.Win32Exception exp )
                {
                    err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
                }
                catch( System.Exception exp )
                {
                    err = String.Format( "Exception: Common: {0}", exp.Message );
                }

                if( terminated )
                    break;

                if( err.Length > 0 )
                {
                    MessageBox.Show( String.Format("The message was unable to delivery to <{0}> due to \r\n{1}",
                        address.Address, err ));

                    sbStatus.Text = err;
                }
            }
        }
开发者ID:DirkViljoen,项目名称:eSalon,代码行数:63,代码来源:Form1.cs

示例5: button1_Click


//.........这里部分代码省略.........
                }

                SmtpServer oServer = new SmtpServer( textServer.Text );
                oServer.Protocol = (ServerProtocol)lstProtocol.SelectedIndex;

                if( oServer.Server.Length != 0 )
                {
                    if( chkAuth.Checked )
                    {
                        oServer.User = textUser.Text;
                        oServer.Password = textPassword.Text;
                    }

                    if( chkSSL.Checked )
                        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                }
                else
                {
                    //To send email to the recipient directly(simulating the smtp server),
                    //please add a Received header,
                    //otherwise, many anti-spam filter will make it as junk email.
                    System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                    string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                    gmtdate.Remove( gmtdate.Length - 3, 1 );
                    string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                        oServer.HeloDomain,
                        gmtdate );

                    oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                }

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EASendMail EventHandler region
                oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                if( oServer.Server.Length == 0 && oMail.Recipients.Count > 1 )
                {
                    //To send email without specified smtp server, we have to send the emails one by one
                    // to multiple recipients. That is because every recipient has different smtp server.
                    _DirectSend( ref oMail, ref oSmtp );
                }
                else
                {
                    sbStatus.Text = "Connecting ... ";
                    pgSending.Value = 0;

                    oSmtp.SendMail( oServer, oMail  );

                    MessageBox.Show( String.Format( "The message was sent to {0} successfully!",
                        oSmtp.CurrentSmtpServer.Server ));

                    sbStatus.Text = "Completed";
                }
                //If you want to reuse the mail object, please reset the Date and Message-ID, otherwise
                //the Date and Message-ID will not change.
                //oMail.Date = System.DateTime.Now;
                //oMail.ResetMessageID();
                //oMail.To = "[email protected]";
                //oSmtp.SendMail( oServer, oMail );
            }
            catch( SmtpTerminatedException exp )
            {
                err = exp.Message;
            }
            catch( SmtpServerException exp )
            {
                err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
            }
            catch( System.Net.Sockets.SocketException exp )
            {
                err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
            }
            catch( System.ComponentModel.Win32Exception exp )
            {
                err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
            }
            catch( System.Exception exp )
            {
                err = String.Format( "Exception: Common: {0}", exp.Message );
            }

            if( err.Length > 0  )
            {
                MessageBox.Show( err );
                sbStatus.Text = err;
            }
            //to get more debug information, please use
            //MessageBox.Show( oSmtp.SmtpConversation );

            btnSend.Enabled = true;
            btnCancel.Enabled = false;
        }
开发者ID:DirkViljoen,项目名称:eSalon,代码行数:101,代码来源:Form1.cs

示例6: btnSimple_Click


//.........这里部分代码省略.........
                        if( chkSSL.Checked )
                            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    }
                    else
                    {
                        //To send email to the recipient directly(simulating the smtp server),
                        //please add a Received header,
                        //otherwise, many anti-spam filter will make it as junk email.
                        System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                        string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                        gmtdate.Remove( gmtdate.Length - 3, 1 );
                        string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                            oServer.HeloDomain,
                            gmtdate );

                        oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                    }

                    //Catching the following events is not necessary,
                    //just make the application more user friendly.
                    //If you use the object in asp.net/windows service or non-gui application,
                    //You need not to catch the following events.
                    //To learn more detail, please refer to the code in EASendMail EventHandler region
                    oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                    oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                    oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                    oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                    oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                    _CrossThreadSetItemText( "Connecting...", index );
                    if(!chkTestRecipients.Checked)
                    {
                        oSmtp.SendMail( oServer, oMail  );
                        _CrossThreadSetItemText( "Completed", index );
                    }
                    else
                    {
                        oSmtp.TestRecipients( null, oMail );
                        _CrossThreadSetItemText( "PASS", index );
                    }

                    m_nsuccess ++;
                    //If you want to reuse the mail object, please reset the Date and Message-ID, otherwise
                    //the Date and Message-ID will not change.
                    //oMail.Date = System.DateTime.Now;
                    //oMail.ResetMessageID();
                    //oMail.To = "[email protected]";
                    //oSmtp.SendMail( oServer, oMail );
                }
                catch( SmtpTerminatedException exp )
                {
                    err = exp.Message;
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( SmtpServerException exp )
                {
                    err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( System.Net.Sockets.SocketException exp )
                {
                    err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
                    _CrossThreadSetItemText( err, index );
开发者ID:DirkViljoen,项目名称:eSalon,代码行数:67,代码来源:Form1.cs

示例7: SendShipConfirmations

        public static int SendShipConfirmations()
        {
            int count = 0;
            int grcount = 0;
            int grocount = 0;
            int grecount = 0;
            int grgcount = 0;
            int grpcount = 0;

            string smtpServer = Databases.serverModel.RegistrySet.Find("smtp_server").Value;
            string emailUser = Databases.serverModel.RegistrySet.Find("email_user").Value;
            string emailPassword = Databases.serverModel.RegistrySet.Find("email_pass").Value;
            string emailFrom = Databases.serverModel.RegistrySet.Find("email_from").Value;
            Email mail = Databases.serverModel.EmailSet.Find("Szállítási értesítő");

            XDocument feedback = new XDocument();
            XElement groot = new XElement("Feedback");
            XDocument grofeedback = new XDocument();
            XElement groroot = new XElement("Feedback");
            XDocument grefeedback = new XDocument();
            XElement greroot = new XElement("Feedback");
            XDocument grgfeedback = new XDocument();
            XElement grgroot = new XElement("Feedback");
            XDocument grpfeedback = new XDocument();
            XElement grproot = new XElement("Feedback");

            groot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            groroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            greroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            grgroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            grproot.SetAttributeValue("action", GruppiFeedbackAction.send_message);

            List<Order> _orders = Databases.serverModel.OrderSet.Where(x =>x.Emails_in_order.Count == 1 && x.Completed==true).ToList();

            foreach (Order o in _orders)
            {
                string message = mail.Message;
                System.Reflection.PropertyInfo[] _properties = typeof(Order).GetProperties();
                var q = from x in _properties
                        select x.Name;
                List<string> _props = q.ToList();

                foreach (string s in _props)
                {
                    if (message.Contains("&lt;&lt;" + s + "&gt;&gt;"))
                        message = message.Replace("&lt;&lt;" + s + "&gt;&gt;", o.GetType().GetProperty(s).GetValue(o).ToString());
                }

                if (o.Partner_site.Name.StartsWith("Gruppi"))
                {
                    message = message.Replace("<HTML>", "").Replace("</HTML>", "").Replace("<BODY>", "").Replace("</BODY>", "");
                    XElement gmessage = new XElement("Message");
                    gmessage.Add(new XElement("order_id",o.External_Id));
                    gmessage.Add(new XElement("From", emailFrom + "," + emailUser));
                    gmessage.Add(new XElement("To", o.External_Id));
                    gmessage.Add(new XElement("Subject", o.Partner_site.Name + " Értesítés megrendelt termék kiszállításáról"));
                    gmessage.Add(new XElement("Body", message));
                    o.Emails_in_order.Add(new Email_in_order { Date = DateTime.Now, Email = mail, Sent = true });
                    Databases.serverModel.SaveChanges();
                    switch (o.Partner_site.Name)
                    {
                        case ("Gruppi"): { groot.Add(gmessage); grcount++; break; }
                        case ("Gruppi Otthon"): { groroot.Add(gmessage); grocount++; break; }
                        case ("Gruppi Egészség"): { greroot.Add(gmessage); grecount++; break; }
                        case ("Gruppi Gasztró"): { grgroot.Add(gmessage); grgcount++; break; }
                        case ("Gruppiac"): { grproot.Add(gmessage); grpcount++; break; }
                    }

                }
                else
                {
                    SmtpMail oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();

                    oMail.From = new MailAddress(emailFrom, emailUser);
                    string emailadd = "";
                    if (o.Email != null && o.Email.Length > 0)
                        emailadd = o.Email;
                    oMail.To = emailadd;//"[email protected]";
                    oMail.Subject = mail.Subject;
                    oMail.HtmlBody = message;
                    SmtpServer oServer = new SmtpServer(smtpServer);
                    oServer.User = emailUser;
                    oServer.Password = emailPassword;
                    oServer.Port = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    try
                    {
                        oSmtp.SendMail(oServer, oMail);
                        o.Emails_in_order.Add(new Email_in_order { Date = DateTime.Now, Email = mail, Sent = true });
                        Databases.serverModel.SaveChanges();
                        count++;
                    }
                    catch (Exception ex)
                    {
                        return -1;
                    }
                }
            }
            if (grcount > 0)
//.........这里部分代码省略.........
开发者ID:pellicerrobert,项目名称:IRIS,代码行数:101,代码来源:ServerFunctions.cs

示例8: button2_Click

        private void button2_Click(object sender, EventArgs e)
        {
            //supplier notification
            int bob;
            bob = cmbSupplier.SelectedIndex;

            string value = "Brand\t\t\tProduct\t\t\tQuantity\r\n";

                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    value += dataGridView1.Rows[i].Cells[0].Value + "\t\t" +
                            dataGridView1.Rows[i].Cells[1].Value + "\t\t" +
                            dataGridView1.Rows[i].Cells[2].Value + "";
                }

            try
            {

                SmtpMail oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();

                oMail.From = "[email protected]";
                oMail.To = //spl[bob].Email;
                oMail.Subject = "Order Placed";
                oMail.TextBody = value;

                SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                oServer.User = "[email protected]";
                oServer.Password = "esLuaxeiri1";
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                oServer.Port = 465;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                try
                {
                    oSmtp.SendMail(oServer, oMail);
                    MessageBox.Show("Email was sent successfully!");

                }
                catch (Exception ep)
                {
                    MessageBox.Show("Failed to send email with the following error: ");
                    MessageBox.Show(ep.Message);
                }
            }
            catch (Exception d)
            {
                MessageBox.Show("EMAIL ERROR: " + d);
            }
        }
开发者ID:DirkViljoen,项目名称:eSalon,代码行数:50,代码来源:AddOrder.cs


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