具體的上傳頁面實現,請見下文:
看到上傳頁面,控件很少:1個FileUpload、4個TextBox和1個Button。通過VS的界面設計器直接拖放出來。還有隱藏的3個驗證控件:2個Request和1個郵件格式驗證。
按鈕OnClick事件代碼:
protected void btnUpload_Click(object sender, EventArgs e)
{
string mess = "Nickname: "+txtNickname.Text + "<br />Link: " + txtLink.Text+"<br />Comments: "+txtComments.Text;
try
{
SendMail("[email protected]", "[email protected]", fuFile.FileName + " uploaded", mess, txtEmail.Text, true, fuFile.FileName, fuFile.FileBytes, "smtphost", "username", "password");
Response.Redirect("upload_thankyou.html",true);
}
catch(Exception ex)
{
lblMsg.Text = ex.Message;
}
}
通過fuFile.FileBytes得到客戶端上傳的文件內容,並調用SendMail函數發送附件到指定的郵箱。SendMail代碼如下:
public static void SendMail(string from, string to, string subject, string message, string replyto, bool hasatt, string filename, byte[] att, string host, string username, string password)
{
MailMessage em = new MailMessage(from, to);
em.Subject = subject;
em.Body = message;
em.IsBodyHtml = true;
if (replyto.Length > 0) em.ReplyTo = new MailAddress(replyto);
if (hasatt)
{
Stream s = (Stream)(new MemoryStream(att));
em.Attachments.Add(new Attachment(s, filename));
}
SmtpClient sc = new SmtpClient(host);
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential oCredential = new System.Net.NetworkCredential(username, password);
sc.UseDefaultCredentials = false;
sc.Credentials = oCredential;
sc.Send(em);
}
發送完畢跳到Thankyou頁面,大約三五分鐘後指定的郵箱就收到附件了。
來源:http://siguchuan.blog.163.com/blog/static/953551872010101132353328/