我正试图将上传的文件作为附件发送到我的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);
我可以发送没有附件的电子邮件。是否需要先保存文件再添加到附件?
您不需要也不应该不必要地将附件保存到服务器。ASP Snippets有一篇关于如何在ASP中做到这一点的文章。净WebForms。
在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) { }
}
}
跟随Serj Sagan的脚步,这里是一个使用webforms的处理程序,但使用<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"
在您的表单标签。
你可以这样做:
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.";
}
FileName是客户端的文件名,而不是服务器端的文件名。您将需要使用savea或InputStream将任何内容放入附件。
这是MSDN文档的链接