I have an ASPMVC webapi application in which the client will attach an attachment. this attachment is the form byte[]. But on the server side we are not able to receive the attachment.
Here is the client code.
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();
Here is the service Side Code i.e. 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();
}