您的位置:首页 > 编程语言 > C#

C# 附件上传及发送电子邮件实例源代码

2011-03-03 09:43 645 查看
具体的上传页面实现,请见下文:

看到上传页面,控件很少: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("webmaster@yunyblog.com", "royhwa@gmail.com", 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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: