从MVC方法调用WebAPI方法传递邮件消息

时间:2017-06-09 14:35:44

标签: c# .net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我的MVC控制器中有一个方法,我试图调用API来发送电子邮件(邮件消息是在MVC方法中生成的)

创建邮件消息如下,这样可以正常工作。

    public static MailMessage CreateMailMessage(string from,
        string to,
        string cc,
        string bcc,
        string subject,
        string body,
        List<Attachment> attachments,
        string differentServer,
        bool eatError)
    {
        MailMessage mm = new MailMessage();
        mm.From = new MailAddress(from);
        mm.Subject = subject;
        mm.Body = body;
        mm.IsBodyHtml = true;

        //send to multiple addresses separated by semi-colon or comma      
        if (!string.IsNullOrEmpty(to))
        {
            var toAddresses = to.Split(new char[] { ';', ',' });
            foreach (string toAddress in toAddresses)
            {
                if (!string.IsNullOrWhiteSpace(toAddress))
                    mm.To.Add(toAddress);
            }
        }

        if (!string.IsNullOrEmpty(cc))
        {
            mm.CC.Add(cc);
        }

        if (!string.IsNullOrEmpty(bcc))
        {
            mm.Bcc.Add(bcc);
        }

        if (attachments != null)
        {
            foreach (Attachment attachment in attachments)
            {
                mm.Attachments.Add(attachment);
            }
        }
        return mm;
    }

然而,为了发送我需要编写的电子邮件并调用WebAPI方法 - 发送电子邮件很好 - 只是不确定如何将邮件消息和其他一些属性发布到WebAPI方法?

所以我的WebAPI方法就像:

    /// <summary>
    /// Method to email the Report
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [Route("api/Document/EmailReport/")]
    public HttpResponseMessage EmailFarmFeatures([FromBody]MailMessage email)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }

我试图从MVC方法中调用此WebAPI,如下所示:

private void EmailReport(string reportName, byte[] bytes)
{
  ContentType ct = new ContentType(MediaTypeNames.Application.Octet);
  var attachments = new List<Attachment>();
  var attach = new Attachment(new MemoryStream(bytes), ct);
  attach.ContentDisposition.FileName = reportName;
  attachments.Add(attach);

  string strFrom = ConfigurationManager.AppSettings["FromEmail"];
  string strTo = ConfigurationManager.AppSettings["ToEmail"];

  string subject = string.Format("Customer Report - {0}", customerId);
  string body = string.Format("Report for Customer {0} attached.", customerId);
  string mailServer = ConfigurationManager.AppSettings["SmtpServer"];

  MailMessage message = EmailHelper.CreateMailMessage(strFrom, strTo, "", "", subject, body, attachments, mailServer, false);

  using (var client = new HttpClient())
  {
    var requestBody = JsonConvert.SerializeObject(message);
    var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");

    var response = client.PostAsync("http://localhost/myWS/api/Document/EmailReport/", postRequest).GetAwaiter().GetResult();

    if (response.StatusCode != HttpStatusCode.OK)
    {
      throw new Exception("Error occured emailing report");
    }
  }
}

我目前在这一行收到错误:

var requestBody = JsonConvert.SerializeObject(message);

[InvalidOperationException: Timeouts are not supported on this stream.]
   System.IO.Stream.get_ReadTimeout() +57
   GetReadTimeout(Object ) +81
   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +114

[JsonSerializationException: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.]
   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +274

我认为这与使用内存流附件的尝试有关,虽然我不确定是什么修复以确保此附件包含在API方法的POST请求中

1 个答案:

答案 0 :(得分:0)

MailMessage不可序列化只需创建一个表示邮件消息的独立常规对象。

看一下这个主题,我想它几乎就是你所需要的:

https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5)[https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5]