using System.Web.Mail;
using System.IO;
private void btnSend_Click(object sender, System.EventArgs e)
{
//分別取得郵件的收信人的地址、發信人的地址、抄送、主題、內容等資訊
string strTo = tbTo.Text;
string strFrom = tbFrom.Text;
string strPwd = tbPwd.Text;
string strCopyTo = tbCopyTo.Text;
string strSubject = tbSubject.Text;
string strBody = tbBody.Text;
try
{
MailMessage ms=new MailMessage();
ms.To = strTo; //收信人的地址
ms.From = strFrom; //發信人的地址
ms.Cc = strCopyTo; //抄送
ms.Subject = strSubject; //主題
ms.BodyFormat = MailFormat.Html; //本文格式html/text
ms.Body = strBody; //本文
string strPathOfAttachFile = ""; //初始化附件
//如果有附件則上傳
HttpPostedFile hpPFile = AttachFile.PostedFile; //獲得上傳檔案的訪問
if(hpPFile.FileName != "")
{
//有附件,則上傳到Temp目錄中
//判斷是否存在Temp目錄,若無,則建立
string FolderName = Server.MapPath(".") + "\\Temp";
if(Directory.Exists(FolderName) == false)
Directory.CreateDirectory(FolderName);
//取得檔案名稱(不含路徑)
char[] separator = {'\\'}; //separator的值為"\"
string[] AFileName = hpPFile.FileName.Split(separator);
string strFileName = AFileName[AFileName.Length-1];
strPathOfAttachFile = Server.MapPath(".")+"\\Temp\\"+strFileName;
hpPFile.SaveAs(strPathOfAttachFile);
//添加附件
ms.Attachments.Add(new MailAttachment(strPathOfAttachFile));
}
//從發信人的地址計算出郵件伺服器
string[] strTemp = strFrom.Split('@');
string strPartOfSmtpServer = strTemp[strTemp.Length-1];
string strSmtpServer = "smtp." + strPartOfSmtpServer;
ms.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//value=0 No Check value=1 Basic Check Value=2 Exchage Check
ms.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", strFrom); //發信人的郵箱地址
ms.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", strPwd);//驗證資訊
SmtpMail.SmtpServer=strSmtpServer; //郵件伺服器ip或網域名稱
SmtpMail.Send(ms); //發送
//清除控制項中的內容
tbTo.Text = "";
tbCopyTo.Text = "";
tbSubject.Text = "";
tbBody.Text = "";
//刪除Temp目錄中的附件
if(File.Exists(strPathOfAttachFile) == true)
File.Delete(strPathOfAttachFile);
//確認郵件發送成功
string strScript = "<script>alert('郵件發送成功!')</script>";
if (! Page.IsStartupScriptRegistered("Alert"))
{
Page.RegisterStartupScript("Alert", strScript);
}
}
catch
{
string strScript = "<script>alert('郵件發送失敗!')</script>";
if (! Page.IsStartupScriptRegistered("Alert"))
{
Page.RegisterStartupScript("Alert", strScript);
}
}
}