Send Uploaded File as attachment
You can do like this:
private void btnSend_Click(object sender,EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.To = this.txtTo.Text;
myMail.From = "<" + this.txtFromEmail.Text + ">" + this.txtFromName.Text;
myMail.Subject = this.txtSubject.Text;
myMail.BodyFormat = MailFormat.Html;
myMail.Body = this.txtDescription.Text.Replace("\n","<br>");
//*** Files 1 ***//
if(this.fiUpload1.HasFile)
{
this.fiUpload1.SaveAs(Server.MapPath("MyAttach/"+fiUpload1.FileName));
myMail.Attachments.Add(new MailAttachment(Server.MapPath("MyAttach/"+fiUpload1.FileName)));
}
//*** Files 2 ***//
if(this.fiUpload2.HasFile)
{
this.fiUpload2.SaveAs(Server.MapPath("MyAttach/"+fiUpload2.FileName));
myMail.Attachments.Add(new MailAttachment(Server.MapPath("MyAttach/"+fiUpload2.FileName)));
}
SmtpMail.Send(myMail);
myMail = null;
this.pnlForm.Visible = false;
this.lblText.Text = "Mail Sending.";
}
You do NOT need to, nor should you, save attachments to the server unnecessarily. ASP Snippets has an article on how to do it in ASP.NET WebForms.
Doing it in C# MVC is even nicer:
public IEnumerable<HttpPostedFileBase> UploadedFiles { get; set; }
var mailMessage = new MailMessage();
// ... To, Subject, Body, etc
foreach (var file in UploadedFiles)
{
if (file != null && file.ContentLength > 0)
{
try
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
mailMessage.Attachments.Add(attachment);
}
catch(Exception) { }
}
}
Following in the footsteps of Serj Sagan, here's a handler using webforms, but with <input type="file" name="upload_your_file" />
instead of the <asp:FileUpload>
control:
HttpPostedFile file = Request.Files["upload_your_file"];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
mailMessage.Attachments.Add(attachment);
}
This is useful if you don't need (or can't add) a runat="server"
on your form tag.