C# - 利用 Gmail SMTP 幫你寄信

C# - 利用 Gmail SMTP 幫你寄信

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. }