備忘:需要引入兩個命名空間
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");