只要有 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." );
}
}
}
}
特別要注意的是 Port, 一般都寫 465,
但實際試過 465 都不行, 網上寫 587,... 就口以!!
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.Port = 587
smtp.Credentials = New System.Net.NetworkCredential("帳號", "密碼")
smtp.EnableSsl = True
Dim fromAddress As New MailAddress(strFromMail, strFromName)
Dim toAddress As New MailAddress(strToMail, strToName)
Dim mailMessage1 As New MailMessage(fromAddress, toAddress)
mailMessage1.Subject = "主旨"
mailMessage1.Body = "郵件內文"
Try
smtp.Send(mailMessage1)
mailMessage1.Dispose()
Catch ex As Exception
Response.Write("ERROR!!")
End Try
smtp = Nothing
== 分隔線 ==
除了寄件外, 還必須了解 gmail l的一些限制,..
Gmail原來都有一定的限制。這些限制其實是避免有人利用Gmail在不軌的用途上。
首先,如果你透過Email Client,以POP或IMAP發電郵,一封郵件最多只可以發給100人,否則你的Gmail帳號便會被停用一天。
以Web Interface來用Gmail,這個限額就大很多──500人。但如果你發給500人以上,你的帳號可能會被停用24-72小時不等。
不過,一般用戶都應該衝不過100,甚至500這兩個大限。如果多於這大限,或許意味著發信人是個Spammer吧。
還有一個有趣的限制。如果一封郵件內有很多的失效電郵地址,會引致大量Bounce Back的話,你的帳號也可能會被停用。