.net System.Web.Mail傳送郵件的實際應用程式碼

yuzhangqi發表於2008-12-17

本例項程式碼實現:

1. 構造一個EmailMessage物件例項;

2. 讀取配置檔案的郵件傳送設定,如SMTP Server, UserName,Password,是否需要驗證;

3. 異常處理;

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mail;
using System.IO;

namespace Service.MailService
{
///


/// 郵件傳送器。
///

public class EmailSender
{
///
/// 執行Email傳送動作
///

///
private void Send(EmailMessage item)
{
MailMessage mail = new MailMessage();
mail.From = item.From;
mail.To = item.To;
mail.Subject = item.Subject;
mail.Body = item.Message;
mail.BodyFormat = MailFormat.Html;

if (mail.To.Equals(string.Empty) || (!Validator.CheckEmailAddress(mail.To)))
{
throw new Exception("無效的郵件地址。");
}

bool needAuthenticeate = Convert.ToBoolean(ConfigReader.GetValueByKeyFromConfigFile("NeedAuthenticate"));
if (needAuthenticeate)
{
string userName = ConfigReader.GetValueByKeyFromConfigFile("AuthorizedUser");
string password = ConfigReader.GetValueByKeyFromConfigFile("AuthorizedPassword");

mail.Fields.Add(""); //basic authentication
mail.Fields.Add("", userName); //set your username here
mail.Fields.Add("", password); //set your password here
}

string file = item.Attachment;
try
{
if (File.Exists(file))
{
MailAttachment attachment = new MailAttachment(file,MailEncoding.Base64);
mail.Attachments.Add(attachment);
}

SmtpMail.SmtpServer = ConfigReader.GetValueByKeyFromConfigFile("SmtpServer");
SmtpMail.Send(mail);
}
catch (Exception ex)
{
throw new Exception("郵件傳送中出現異常,請聯絡郵件伺服器管理員。",ex);
}
}

}
}

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/13651903/viewspace-1014817/,如需轉載,請註明出處,否則將追究法律責任。

相關文章