SmtpClient使用介紹

來源:互聯網
上載者:User

備忘:需要引入兩個命名空間

using System.Net.Mail;
using System.Net;

程式部分:

private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();//退出程式
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                G_Attachment.Text = openFileDialog1.FileName;//擷取附件。
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string MyPsd = G_password.Text;
            string MyEmail = G_email.Text.Trim() + "@gmail.com";
            MailMessage MMsg = new MailMessage();
            MMsg.Subject = G_subject.Text.Trim();
            MMsg.From = new MailAddress(MyEmail);
            MMsg.To.Add(new MailAddress(G_address.Text.Trim()));
            MMsg.IsBodyHtml = true;//這裡啟用IsBodyHtml是為了支援內容中的Html。
            MMsg.BodyEncoding = Encoding.UTF8;//將本文的編碼形式設定為UTF8。
            MMsg.Body = G_content.Text;
            SmtpClient SClient = new SmtpClient();
            SClient.Host = "smtp.gmail.com";//google的smtp地址
            SClient.Port = 587;//google的smtp連接埠
            SClient.EnableSsl = true;//因為google使用了SSL(安全通訊端層)加密連結所以這裡的EnableSsl必須設定為true。
            SClient.Credentials = new NetworkCredential(MyEmail, MyPsd);
            if (G_Attachment.Text.Length>0)
            {
                MMsg.Attachments.Add(new Attachment(G_Attachment.Text));//判斷是否有附件
            }
            try
            {
                SClient.Send(MMsg);
                MessageBox.Show("郵件已經發送成功");
            }
            catch (Exception err)
            {

                MessageBox.Show(err.Message, "錯誤提示");
            }

         }

 執行個體2:

           string to = "get@tom.com";
           string from = "set@tom.com";
           MailMessage message = new MailMessage(from, to);
           message.Subject = "Using the new SMTP client測試郵件.";
           message.Body = @"測試郵件.";
           SmtpClient client = new SmtpClient("smtp.tom.com",25);
           // Credentials are necessary if the server requires the client
             // to authenticate before it will send e-mail on the client's behalf.
           client.Credentials = new NetworkCredential("set@tom.com","****");  //指定發送的使用者名稱,密碼
            client.Send(message);
            MessageBox.Show("發送成功ok");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.