只要有 Gmail 個人帳號與密碼,透過 Gmail SMTP SSL 的認證,Gmail 就可以幫助你寄信囉!
該程式利用 MailAddress 建立收發信人的郵件位址,MailMessage 建立郵件相關內容,SmtpClient 與 NetworkCredential 建立 Smtp 連線認證與寄信功能。
程式碼:
-
using System;
-
using System.ComponentModel;
-
using System.Net;
-
using System.Net.Mail;
-
using System.Text;
-
using System.Windows.Forms;
-
namespace MyMail
-
{
-
public partial class Form1 : Form
-
{
-
public Form1( )
-
{
-
InitializeComponent( );
-
}
-
private void button1_Click_1( object sender, EventArgs e)
-
{
-
// Mail Message Setting
-
string fromEmail = "XXX@gmail.com";
-
string fromName = "C.H.Huang";
-
MailAddress from = new MailAddress (fromEmail, fromName, Encoding. UTF8 );
-
string toEmail = "YYY@gmail.com";
-
MailMessage mail = new MailMessage (from, new MailAddress (toEmail ) );
-
string subject = "Test Subject";
-
mail.Subject = subject;
-
mail.SubjectEncoding = Encoding.UTF8;
-
string body = "Test Body";
-
mail.Body = body;
-
mail.BodyEncoding = Encoding.UTF8;
-
mail.IsBodyHtml = false;
-
mail.Priority = MailPriority.High;
-
// SMTP Setting
-
SmtpClient client = new SmtpClient ( );
-
client.Host = "smtp.gmail.com";
-
client.Port = 587;
-
client. Credentials = new NetworkCredential ( "username@gmail.com", "password" );
-
client.EnableSsl = true;
-
// Send Mail
-
client.SendAsync (mail, mail);
-
// Sent Compeleted Eevet
-
client. SendCompleted += new SendCompletedEventHandler (client_SendCompleted );
-
}
-
// Handle Sent Compeleted Eevet
-
private void client_SendCompleted( object sender, AsyncCompletedEventArgs e)
-
{
-
if (e.Error != null )
-
{
-
MessageBox.Show (e.Error.ToString ( ) );
-
}
-
else
-
{
-
MessageBox.Show ( "Message sent." );
-
}
-
}
-
}
-
}
|