使用System.Web.Mail發送郵件:
public void SendMail()
{
MailMessage mail1 = new MailMessage();
mail1.Body="body here"; //郵件的本文
mail1.From="xxx@your.com"; //發信人的地址
mail1.To="yyy@their.com"; //收信人的地址
mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1); //要求smtp認證
mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername","xxx"); //smtp認證的使用者
mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword","********"); //smtp認證的密碼
SmtpMail.SmtpServer="mail.your.com"; //smtp伺服器
SmtpMail.Send(mail1); //發送郵件
}
使用System.Net.Mail發送郵件:
發現用這種方式發郵件,如果發郵件的電腦開啟了殺毒軟體的郵件監控,會有錯誤提示,但能夠發信成功。
1)第一種方式:先配置web.config檔案
<system.net>
<mailSettings>
<smtp from="your@your.com">
<network host="smtp.your.com" port="25" userName="your" password="yourpass" />
</smtp>
</mailSettings>
</system.net>
然後通下面的程式發信:
private void SendMail()
{
SmtpClient smtp = new SmtpClient();
MailMessage message = new MailMessage();
message.To.Add("to@yourmail.com"); //收信人地址
message.SubjectEncoding = System.Text.Encoding.UTF8; //主題文字編碼方式
message.BodyEncoding = System.Text.Encoding.UTF8; //內容文字編碼方式
message.Subject = "A test for sending mail"; //主題
message.Body = "Thanks for your sending mail./n/n"; //內容
smtp.Send(message); //發信
message.Dispose();
}
2)第二種方式是不配置web.config檔案,直接通過下面的程式發信:
private void SendMail()
{
SmtpClient smtp = new SmtpClient("mail.your.com", 25);
smtp.Credentials = new System.Net.NetworkCredential("from@your.com", "yourpass"); //提供發信smtp認證資訊
MailAddress from = new MailAddress("from@your.com", "tiger", System.Text.Encoding.UTF8); //發信人資訊
MailAddress to = new MailAddress("to@their.com"); //收信人資訊
MailMessage message = new MailMessage(from, to);
message.Subject = "這裡是主題";
message.Body = "本文內容";
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
smtp.Send(message);
message.Dispose();
}