始找的代碼只能發送無SMTP驗證的郵件,但現在很多EMAIL發送時都需要驗證,後來查找了下MSDN的幫助,找到了發送驗證的代碼,貼出來希望對大家有所幫助!
復制代碼 代碼如下:
public static int sendmail(string to, string body,string subject)
{
try
{
int nContain = 0;
///添加發件人地址
string from = "你的發送EMAIL";
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress(from);
nContain += mailMsg.From.Address.Length;
///添加收件人地址
mailMsg.To.Add(to);
nContain += mailMsg.To.ToString().Length;
///添加郵件主題
mailMsg.Subject = subject;
mailMsg.SubjectEncoding = Encoding.UTF8;
nContain += mailMsg.Subject.Length;
///添加郵件內容
mailMsg.Body = body;
mailMsg.BodyEncoding = Encoding.UTF8;
mailMsg.IsBodyHtml = true;
nContain += mailMsg.Body.Length;
if (mailMsg.IsBodyHtml == true)
{
nContain += 100;
}
///發送郵件
try
{
//定義發送郵件的Client
SmtpClient client = new SmtpClient();
//表示以當前登錄用戶的默認憑據進行身份驗證
client.UseDefaultCredentials = true;
//包含用戶名和密碼
client.Credentials = new System.Net.NetworkCredential(application.GetapplicationSendmail(), application.GetapplicationSendpass());
///設置郵件服務器主機的IP地址
client.Host = "SMTP服務器IP"
///設置郵件服務器的端口
client.Port = 25;
///配置發送郵件的屬性
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(strFrom, strto, strSubject, strBody);
mailMsg.Priority = System.Net.Mail.MailPriority.Normal;
//client.UseDefaultCredentials = false;
///發送郵件
client.Send(mailMsg);
return 1;
}
catch (Exception ex) { return 0; }
}
catch (Exception ex) { return 0; }
}