如何使用asp.net mvc webapi发送电子邮件附件

时间:2015-03-04 04:52:13

标签: c# asp.net asp.net-mvc-3 asp.net-mvc-4 razor

我有一个ASPMVC webapi应用程序,客户端将在其中附加附件。 这个附件是表格byte []。但在服务器端,我们无法收到附件。

这是客户端代码。

StringBuilder sbAPIRequest = new StringBuilder();
sbAPIRequest.Append("http://localhost:58229/api/SendEmailMessage");
sbAPIRequest.Append("&From=");
sbAPIRequest.Append(request.From);
sbAPIRequest.Append("&Subject=");
sbAPIRequest.Append(request.Subject);
sbAPIRequest.Append("&To=");
sbAPIRequest.Append(request.To);
sbAPIRequest.Append("&FileName=");
sbAPIRequest.Append(request.FileName);
sbAPIRequest.Append("&Body=");
sbAPIRequest.Append(request.Body);
sbAPIRequest.Append("&Data=");
sbAPIRequest.Append(System.IO.File.ReadAllBytes("File Path"));
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(sbAPIRequest.ToString());
httpWReq.Method = "GET";
httpWReq.ContentType = "application/json;charset=UTF-8";
httpWReq.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

这是服务旁边代码,即ASPMVC webapi

public IEnumerable<string> Get([FromUri] Models.EmailMessageRequest emailMessage)
        {
            MailMessage _MailMessage = new MailMessage();
            System.Net.Mail.Attachment attachment;
            List<string> Messages = new List<string>();    
            try
            {
                        UpdateMailAddressCollection(_MailMessage.Bcc, emailMessage.Bcc);
                        _MailMessage.Body = emailMessage.Body;
                        UpdateMailAddressCollection(_MailMessage.CC, emailMessage.CC);
                        _MailMessage.From = getMailAddress(emailMessage.From);
                        _MailMessage.IsBodyHtml = emailMessage.IsBodyHtml;
                        _MailMessage.Subject = emailMessage.Subject;
                        UpdateMailAddressCollection(_MailMessage.To, emailMessage.To);
                        _MailMessage.Priority = getPriority(emailMessage.Priority);

                        if (emailMessage.Data != null && emailMessage.Data[0] != 0)
                        {
                            Stream _Stream = new MemoryStream(emailMessage.Data);
                            attachment = new Attachment(_Stream, emailMessage.FileName);
                            _MailMessage.Attachments.Add(attachment);
                        }
                        string _smtp_host = (new S2.Services.Contracts.Schemas.Customer.AppSettingHelper()).smtp_host;
                        SmtpClient client = new SmtpClient(_smtp_host);
                        client.Send(_MailMessage);
                        response.Success = true;
                        response.Messages.Add("Email Sent successfully.");
            }
            catch (Exception ex)
            {
                response.Messages.Add("Internal Exception");
                response.Success = false;
            }

            Messages.Add(response.Messages.Select(x => x).FirstOrDefault() + " Success:" + response.Success);
            return Messages.ToList();
        }

2 个答案:

答案 0 :(得分:2)

使用网络API发送带附件的电子邮件可以非常简单的方式完成。

在服务方面,即使用system.NET.Mail在C#中完成发送带附件的电子邮件的webapi代码。

以下是客户端向webapi发送附件时遇到的主要问题。 如果客户端正在使用HttpWebRequest,即使用URL发送数据,那么URL有一个限制,即URL可以携带2045字节的数据。如果附加了一个大尺寸文件,则它无法携带附件。

上述解决方案是以下列方式使用HTTPClinet,您可以在其中发送所需大小的附件,其中附件转换为JSON格式。 需要从NUGETS获取HTTPClient。

  HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:58229/");
                client.DefaultRequestHeaders.Clear();

                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage Request = new HttpRequestMessage();
//You need to give the method name
                HttpResponseMessage _response = client.PostAsJsonAsync("api/SendEmail", request).Result;

答案 1 :(得分:0)

您需要将文件内容作为字节数组填充邮件对象。

此链接可能会对您有所帮助

https://codesupport.wordpress.com/2014/05/22/webapi/