Как отправить электронное письмо со страницы просмотра ASP.NET MVC с вложением? - PullRequest
1 голос
/ 06 января 2012

Мне нужно отправить электронное письмо со страницы просмотра контактной формы 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 голосов
/ 06 января 2012

Для получения загруженного файла вам необходимо сделать это

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);

После того, как вы закончите с электронной почтой, удалите файл, созданный на сервере.

Надеюсь, что это отвечает на ваш вопрос

0 голосов
/ 06 января 2012

из 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

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...