Site Meter & 線上人數

tracker

部落格觀察


我的噗浪

Google Latitude

微軟認證



聯絡我 - MSN & Skype & Email



最新回應

C# - 利用 Gmail SMTP 幫你寄信

2008/3/18 19:30| 閱讀數 : 9337 | 我要推薦 | 2 Comments | 文章分類: .NetFramework ASP.Net C# WindowForm 訂閱

Gmail

只要有 Gmail 個人帳號與密碼,透過 Gmail SMTP SSL 的認證,Gmail 就可以幫助你寄信囉!

該程式利用 MailAddress 建立收發信人的郵件位址,MailMessage 建立郵件相關內容,SmtpClientNetworkCredential 建立 Smtp 連線認證與寄信功能。

程式碼:

  1. using System;
  2. using System.ComponentModel;
  3. using System.Net;
  4. using System.Net.Mail;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace MyMail
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1( )
  12. {
  13. InitializeComponent( );
  14. }
  15. private void button1_Click_1( object sender, EventArgs e)
  16. {
  17. // Mail Message Setting
  18. string fromEmail = "XXX@gmail.com";
  19. string fromName = "C.H.Huang";
  20. MailAddress from = new MailAddress(fromEmail, fromName, Encoding.UTF8 );
  21. string toEmail = "YYY@gmail.com";
  22. MailMessage mail = new MailMessage(from, new MailAddress(toEmail) );
  23. string subject = "Test Subject";
  24. mail.Subject = subject;
  25. mail.SubjectEncoding = Encoding.UTF8;
  26. string body = "Test Body";
  27. mail.Body = body;
  28. mail.BodyEncoding = Encoding.UTF8;
  29. mail.IsBodyHtml = false;
  30. mail.Priority = MailPriority.High;
  31. // SMTP Setting
  32. SmtpClient client = new SmtpClient( );
  33. client.Host = "smtp.gmail.com";
  34. client.Port = 587;
  35. client.Credentials = new NetworkCredential( "username@gmail.com", "password" );
  36. client.EnableSsl = true;
  37. // Send Mail
  38. client.SendAsync (mail, mail);
  39. // Sent Compeleted Eevet
  40. client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
  41. }
  42. // Handle Sent Compeleted Eevet
  43. private void client_SendCompleted( object sender, AsyncCompletedEventArgs e)
  44. {
  45. if (e.Error != null )
  46. {
  47. MessageBox.Show (e.Error.ToString ( ) );
  48. }
  49. else
  50. {
  51. MessageBox.Show ( "Message sent." );
  52. }
  53. }
  54. }
  55. }

DotBlogs Tags: .NetFramework ASP.NET C# chhuang WindowForm


關連文章

回應

  • 小明 2009/10/8 下午 06:50 回覆

    # re: C# - 利用 Gmail SMTP 幫你寄信

    大大你好…
    這個範例中
    client.SendAsync (mail, mail);後~
    private void client_SendCompleted
    會於送出完成後才觸發~
    不過如果傳輸時間長,將會不知到傳輸進度為何~
    請問有方法能得知上傳的進度嗎?
  • chhuang 2009/10/8 下午 07:43 回覆

    # re: C# - 利用 Gmail SMTP 幫你寄信

    SmtpClient 有分為 Send() 同步方法與 SendAsync() 非同步方法,請參考 SmtpClient.Send 方法 。 http://msdn.microsoft.com/zh-tw/library/system.net.mail.smtpclient.send.aspx
標題 *
名稱 *
Email (將不會被顯示)
Url
回應
登入後使用進階評論
Please add 8 and 5 and type the answer here: