最近公司讓研究一下發送郵件..試過VB C#感覺還是C#較比穩定些.下面將代碼共享一下 2.0
public class SendMail
...{
private string _host;
public string Host
...{
get ...{ return _host; }
set ...{ _host = value; }
}
private int _port;
public int Port
...{
get ...{ return _port; }
set ...{ _port = value; }
}
private string _smtpUsername;
public string SmtpUsername
...{
get ...{ return _smtpUsername; }
set ...{ _smtpUsername = value; }
}
private string _smtpPassWord;
public string SmtpPassWord
get ...{ return _smtpPassWord; }
set ...{ _smtpPassWord = value; }
}
public void Send(string from, string to, string subject, string body, string[] cc, string[] bcc)
...{
// Create mail message
MailMessage message = new MailMessage(from, to, subject, body);
message.BodyEncoding = Encoding.GetEncoding(936);
if (cc != null && cc.Length > 0)
...{
foreach (string ccAddress in cc)
message.CC.Add(new MailAddress(ccAddress));
}
}
if (bcc != null && bcc.Length > 0)
...{
foreach (string bccAddress in bcc)
...{
message.Bcc.Add(new MailAddress(bccAddress));
}
}
// Send email
SmtpClient client = new SmtpClIEnt(this._host, 25);
if (!String.IsNullOrEmpty(this._smtpUsername) && !String.IsNullOrEmpty(this._smtpPassWord))
clIEnt.Credentials = new NetworkCredential(this._smtpUsername, this._smtpPassWord);
}
clIEnt.EnableSsl = false;
clIEnt.Send(message);
}
調用:
try
...{
SendMail mail = new SendMail();
mail.Host = this.txt_MailServer.Text;//服務器smtp地址
mail.SmtpUsername = this.txt_UserName.Text;//登陸用戶名
mail.SmtpPassWord = this.txt_Pass.Text;//登錄密碼
mail.Send(this.txt_MailAdder.Text, this.txt_toMail.Text, this.txt_title.Text, this.txt_body.Text, null, null);//發件人地址,收件人地址,標題,內容,其他,其他
}
catch (Exception ex)
...{
//可以捕獲異常
}