中央論壇 - CENTER BBS

標題: c#用system.net.mail發信 [打印本頁]

作者: f66666602    時間: 2007-8-14 05:04
標題: c#用system.net.mail發信
  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 = "username@gmail.com";
  19.             string fromName = "username";
  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. }
複製代碼





歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3