如何从带有附件的ASP.NET MVC视图页面发送电子邮件?

时间:2012-01-06 08:19:31

标签: asp.net-mvc-2

我必须从我的ASP.NET MVC 2联系表单视图页面发送一封电子邮件。我需要一个详细的答案,描述如何为此目的创建模型,控制器和视图。这是我的代码在我的控制器类的动作方法中给出..

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SendEMail(CareersEMailModel careersEMailModel,HttpPostedFileBase upload)
{
     if (ModelState.IsValid)
     {
            bool isOK = false;

            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("no-reply@abc.com", "Website contact form");
                msg.To.Add("info@abc.com");
                msg.Subject = "Resume";
                string body = "Name:" + careersEMailModel.Name + "\n" + "Phone:" + careersEMailModel.Phone + "\n" + "Email:" + careersEMailModel.Email;
                string file = careersEMailModel.Resume;
                msg.Body = body;
                msg.IsBodyHtml = false;
                SmtpClient smtp = new SmtpClient("mailserver_url.net", 25);
                smtp.Send(msg);
                msg.Dispose();
                isOK = true;
                CareersMessageModel rcpt = new CareersMessageModel();
                rcpt.Title = "Email sent successfully!!";
                rcpt.Content = "Your details has been received with great thanks.We'll contact you as soon as possible.";
                return View("CareersMessage", rcpt);
            }
            catch (Exception ex)
            {
                CareersMessageModel err = new CareersMessageModel();
                err.Title = "Sorry,Email sending failed!!!";
                err.Content = "The website is having an error with sending this mail at this time.You can send an email to our address provided in our contact us form.Thank you.";
                return View("CareersMessage", err);
            }
        }
        else
        {
            return View();
        }
    }

2 个答案:

答案 0 :(得分:0)

来自MSDN

public static void CreateMessageWithAttachment(string server)
    {
        // Specify the file to be attached and sent.
        // This example assumes that a file named Data.xls exists in the
        // current working directory.
        string file = "data.xls";
        // Create a message and set up the recipients.
        MailMessage message = new MailMessage(
           "jane@contoso.com",
           "ben@contoso.com",
           "Quarterly data report.",
           "See the attached spreadsheet.");

        // Create  the file attachment for this e-mail message.
        Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
        // Add time stamp information for the file.
        ContentDisposition disposition = data.ContentDisposition;
        disposition.CreationDate = System.IO.File.GetCreationTime(file);
        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
        disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
        // Add the file attachment to this e-mail message.
        message.Attachments.Add(data);

        //Send the message.
        SmtpClient client = new SmtpClient(server);
        // Add credentials if the SMTP server requires them.
        client.Credentials = CredentialCache.DefaultNetworkCredentials;

  try {
          client.Send(message);
        }
        catch (Exception ex) {
          Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                ex.ToString() );              
        }
        // Display the values in the ContentDisposition for the attachment.
        ContentDisposition cd = data.ContentDisposition;
        Console.WriteLine("Content disposition");
        Console.WriteLine(cd.ToString());
        Console.WriteLine("File {0}", cd.FileName);
        Console.WriteLine("Size {0}", cd.Size);
        Console.WriteLine("Creation {0}", cd.CreationDate);
        Console.WriteLine("Modification {0}", cd.ModificationDate);
        Console.WriteLine("Read {0}", cd.ReadDate);
        Console.WriteLine("Inline {0}", cd.Inline);
        Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
        foreach (DictionaryEntry d in cd.Parameters)
        {
            Console.WriteLine("{0} = {1}", d.Key, d.Value);
        }
        data.Dispose();
    }

编辑:

Attachment类接受一个流。所以试试吧。 (我没有测试过,但它应该给你你需要做的事情的要点)

foreach (string fileName in Request.Files)
{
    HttpPostedFile file = Request.Files[fileName];

Attachment data = new Attachment(file.InputStream, fileName);
    // do stuff to attach it to the Mail Message

}

答案 1 :(得分:0)

要检索上传的文件,您需要执行此操作

foreach (string file in Request.Files) 
{
    var uploadFile = Request.Files[file];
    if (uploadFile.ContentLength == 0) continue;
    string fileLocation = //File Location with file name, needs to be stored for temporary purpose
    uploadFile.SaveAs(fileLocation);
}

然后在下面的代码的帮助下,您可以附加文件

    Attachment data = new Attachment(fileLocation, MediaTypeNames.Application.Octet);
    message.Attachments.Add(data);

完成电子邮件后,删除在服务器上创建的文件。

希望这能回答你的问题