我正在尝试将上传的文件作为附件发送到我的ashx
文件中。这是我正在使用的代码:
HttpPostedFile fileupload = context.Request.Files[0];
//filename w/o the path
string file = Path.GetFileName(fileupload.FileName);
MailMessage message = new MailMessage();
//*****useless stuff********
message.To.Add("abc@xxx.com");
message.Subject = "test";
message.From = new MailAddress("test@aaa.com");
message.IsBodyHtml = true;
message.Body = "testing";
//*****useless stuff********
//Fault line
message.Attachments.Add(new Attachment(file, MediaTypeNames.Application.Octet))
//Send mail
SmtpClient smtp = new System.Net.Mail.SmtpClient("xxxx", 25);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("xxx", "xxxx");
smtp.Send(message);
我可以发送没有附件的电子邮件。 我是否需要先保存文件然后添加到附件?
答案 0 :(得分:17)
您不需要也不应该不必要地将附件保存到服务器。这是一篇关于如何在ASP.NET WebForms http://www.aspsnippets.com/articles/Attach-files-to-email-without-storing-on-disk-using-ASP.Net-FileUpload-Control.aspx
中执行此操作的文章在C#MVC中实现它甚至更好:
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) { }
}
}
答案 1 :(得分:5)
在Serj Sagan的the footsteps之后,这里是使用网络表单的处理程序,但使用<input type="file" name="upload_your_file" />
代替<asp:FileUpload>
控件:
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);
}
如果您不需要(或无法添加)表单标记上的runat="server"
,这非常有用。
答案 2 :(得分:3)
你可以这样做:
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.";
}
答案 3 :(得分:2)
FileName是客户端上文件的名称,而不是服务器上的文件名。您需要使用SaveAs或InputStream将任何内容添加到附件中。
Here is a link到MSDN文档。