Cannot send email from server - c#

I am trying to make a .net core application that send me an email from an URL.
It works perfectly in my local machine but when i deploy it to my server IIS throws me the next exception:
Insufficient system storage. The server response was: 4.3.1 Insufficient system resources
I don't have this exception when i test it on my machine and the email send correctly, only in the IIS Server is there any configuration that my server need?
here is my code:
MailController.cs
[EnableCors("MyPolicy")]
[Produces("application/json")]
[Route("api/Mail")]
public class MailController : Controller
{
[HttpPost("Send")]
public string Send([FromBody]Correo mail)
{
try
{
MailMessage data = new MailMessage();
data.Body = mail.Body;
if (mail.BodyEncoding != null)
data.BodyEncoding = mail.BodyEncoding;
data.BodyTransferEncoding = mail.BodyTransferEncoding;
data.DeliveryNotificationOptions = mail.DeliveryNotificationOptions;
if (mail.HeadersEncoding != null)
data.HeadersEncoding = mail.HeadersEncoding;
data.Priority = mail.Priority;
if (mail.SubjectEncoding != null)
data.SubjectEncoding = mail.SubjectEncoding;
if (mail.Headers != null)
foreach (NameValueCollection header in mail.Headers)
{
data.Headers.Add(header);
}
if (mail.Attachments != null)
foreach (String att in mail.Attachments)
{
Attachment attachment = new Attachment(att);
data.Attachments.Add(attachment);
}
if (mail.CC != null)
foreach (String cc in mail.CC)
{
data.CC.Add(cc);
}
data.From = new MailAddress(mail.From);
data.IsBodyHtml = mail.IsBodyHtml;
data.Subject = mail.Subject;
foreach (String to in mail.To)
{
data.To.Add(to);
}
SmtpClient smtp = new SmtpClient("<IP of SMTP server>");
smtp.UseDefaultCredentials = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(data);
data.Dispose();
return "Done!";
}
catch (Exception e)
{
return "Mail not send: " + e.Message;
}
}
}
also i send this from an HttpClient from any other code...
AuthOController.cs - Recovery method
[HttpPost("Recovery/{userName}")]
public async Task<IActionResult> Recovery(String userName)
{
try
{
Correo sender = new Correo();
...
...
...
var myContent = JsonConvert.SerializeObject(sender);
var buffer = Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();
var result = await httpClient.PostAsync("http://MailSender/api/Mail/Send", byteContent);
var contents = await result.Content.ReadAsStringAsync();
}
return Ok("Done!");
}
catch (Exception e)
{
return BadRequest(Errors.AddErrorToModelState("recovery_failure", "There was an error in the service: " + e.Message, ModelState));
}
}

data.From = new MailAddress(mail.From);
this line create new object, Change this
For detail help check here

Related

How to Send a MimeMessage

May I know how can I send out a MimeMessage?
Below is my code snippet:
MimeMessage eml = MimeMessage.Load(savedEmlFullFilePath);
MimeMessage toSend = Reply(eml,true); //to send out this message
public static MimeMessage Reply(MimeMessage message, bool replyToAll)
{
var reply = new MimeMessage();
// reply to the sender of the message
if (message.ReplyTo.Count > 0)
{
reply.To.AddRange(message.ReplyTo);
}
else if (message.From.Count > 0)
{
reply.To.AddRange(message.From);
}
else if (message.Sender != null)
{
reply.To.Add(message.Sender);
}
if (replyToAll)
{
reply.To.AddRange(message.To);
reply.Cc.AddRange(message.Cc);
}
// set the reply subject
if (!message.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase))
reply.Subject = "Re:" + message.Subject;
else
reply.Subject = message.Subject;
// construct the In-Reply-To and References headers
if (!string.IsNullOrEmpty(message.MessageId))
{
reply.InReplyTo = message.MessageId;
foreach (var id in message.References)
reply.References.Add(id);
reply.References.Add(message.MessageId);
}
// quote the original message text
using (var quoted = new StringWriter())
{
var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault();
quoted.WriteLine("On {0}, {1} wrote:", message.Date.ToString("f"), !string.IsNullOrEmpty(sender.Name) ? sender.Name : sender.Address);
using (var reader = new StringReader(message.TextBody))
{
string line;
while ((line = reader.ReadLine()) != null)
{
quoted.Write("> ");
quoted.WriteLine(line);
}
}
reply.Body = new TextPart("plain")
{
Text = quoted.ToString()
};
}
return reply;
}
Edit: Would also like to know if it is possible to parse in a MimeMessage into an EmailMessage to I can send it as a ResponseMessage using EWS...
From the MailKit README:
using (var client = new SmtpClient ()) {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect ("smtp.server.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate ("username", "password");
client.Send (message);
client.Disconnect (true);
}

TFS SDK Authentication on IIS

We have an ASP.NET WebAPI which generates a custom document using the TFS SDK. We attempted to wrap the entire call stack for the SDK inside a C# impersonation wrapper. Our document is returned corrupted because the TFS client is not authenticating under the IIS Network Service but is correctly returned with data when we set the App Pool identity to a specific user. The EnsureAuthenticated comes back true. The TestManagementService is not null. The ProjectName parameter is not empty and has a valid ProjectName;
[Route("generatetestplan")]
[HttpPost]
public HttpResponseMessage Post([FromBody]TestPlanRequest Request)
{
var wi = (WindowsIdentity)HttpContext.Current.User.Identity;
HttpResponseMessage Res = new HttpResponseMessage(HttpStatusCode.OK);
WindowsIdentity.RunImpersonated(wi.AccessToken, () =>
{
using (var handler = new HttpClientHandler { UseDefaultCredentials = true })
using (var client = new HttpClient(handler))
{
Res = GenerateTestPlan(Request, Res);
}
});
return Res;
}
public HttpResponseMessage GenerateTestPlan(TestPlanRequest Request, HttpResponseMessage Res)
{
var TestResultsGen = new TestResultsGenerator(Request.ProjectName, Request.TestPlanId);
TestResultsGen.Generate();
var Bytes = TestResultsGen.FBytes;
Res.Content = new ByteArrayContent(Bytes);
Res.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return Res;
}
public TestResultsGenerator(string ProjectName, int TestPlanId)
{
TfsTeamProjectCollection = AuthenticateToCollection();
this.TestPlanId = TestPlanId;
this.ProjectName = ProjectName;
try
{
TestManagementService = TfsTeamProjectCollection.GetService<ITestManagementService>();
TeamProject = TestManagementService.GetTeamProject(ProjectName);
}
catch(Exception e)
{
logger.Error(DateTime.Now.ToString() + " Test Service Error: " + e.ToString());
}
}
public static TfsTeamProjectCollection AuthenticateToCollection()
{
var server = ConfigurationManager.AppSettings["TFS"];
TfsTeamProjectCollection TfsCollection = new TfsTeamProjectCollection(new Uri(server), new Microsoft.VisualStudio.Services.Common.VssCredentials());
try
{
TfsCollection.EnsureAuthenticated();
}
catch (Exception e)
{
logger.Error(e.ToString());
AuthenticateToCollection();
}
return Tfs

Incorporating GZIP into Web API

I have a C# application that communicates to my Web API service fine when there is no GZIP being used. When I apply GZIP, my [FromBody] variable is null and I can't seem to pinpoint why this is happening.
If I put a breakpoint in the web api, I can see that data is null when GZIP is applied. When it's not, it is populated.
Any input would be greatly appreciated. If you need any other code examples please let me know
Update Routing Class
public class UpdateRouting
{
public UpdateRouting()
{
Routes = new List<Routing>();
}
public List<Routing> Routes { get; set; }
}
Collect data
private void btnTestRoutingSend_Click(object sender, EventArgs e)
{
try
{
var response = new ResponseObj();
using (var mainContext = new EntityModel())
{
var nodes = mainContext.Nodes.Where(x => x.SystemType == "Dev").ToList();
var updRouting = new UpdateRouting();
foreach (var n in nodes)
{
using (var nodeContext = new EntityModel(connString))
{
var accounts = nodeContext.Accounts;
foreach (var acct in accounts)
{
//code to map accounts to route
}
var customers = nodeContext.Customers;
foreach (var cust in customers)
{
//code to map customer to route
}
}
}
response = webcontext.SendPost<ResponseObj>(updRouting, "Routing", "SyncRouting");
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
SendPost Method
public T SendPost<T>(object update, string controller, string action)
{
var url = _baseURL + String.Format("api/{0}/{1}", controller, action), update);
T retval = default(T);
var uri = new Uri(_baseUri, url);
try
{
var request = GetRequest(uri, method);
if (content != null)
{
var json = GetBodyString(content);
if (!_useCompression)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var json = GetBodyString(content);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
} else{
using (var gzipStream = new GZipStream(request.GetRequestStream(), CompressionMode.Compress, false))
{
using (var streamWriter = new StreamWriter(gzipStream))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
httpWebRequest.Headers.Add("Content-Encoding", "gzip");
}
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
retval = GetObject<T>(result);
}
}
catch (Exception e)
{
_log.Error(string.Format("Error sending {0} request to {1}", method, uri.ToString()), e);
}
return retval;
}
Get Request
protected virtual HttpWebRequest GetRequest(Uri uri, string method)
{
var retval = (HttpWebRequest)WebRequest.Create(uri);
retval.Timeout = 1000 * 60 * 5;
retval.Accept = "application/json";
retval.KeepAlive = true;
retval.ContentType = "application/json";
retval.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
retval.Method = method;
return retval;
}
API Call
[System.Web.Http.HttpPost]
[Route("SyncRouting")]
public ResponseObj SyncRouting([FromBody] UpdateRouting data)
{
var response = new ResponseObj();
try
{
// do stuff
response.Successful = true;
return response;
}
catch (Exception e)
{
response.Successful = false;
response.Errors.Add(new ErrorMsg
{
Message = "Error - " + e.ToString(),
ExceptionMessage = e.Message,
StackTrace = e.StackTrace,
InnerException = e.InnerException.ToString()
});
return response;
}
}

HttpClient & WebAPI Unpredictable Redirect 302

I have a WPF app that uses HttpClient to call a Web API method on another server. Everything works fine, however, sometimes, especially when the client app wakes up (from power suspend), the call to the same server method returns Found: 302 instead of OK: 200.
The Web API method doesn't really do anything, and it just has an [Authorize] attribute to make sure the user is authenticated. Normally, if the user is not authenticated, it would return 404.
BTW, I'm not using ASP.NET forms authentication explicitly, but the redirect is sending the client to login.aspx, which doesn't exist.
Here's the code:
Web API Method (.NET 4.5):
[HttpGet]
public HttpStatusCodeResult IsAuthenticated()
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}
WPF App client code (.NET 4.0):
public async Task<bool> IsAuthenticated()
{
try
{
Uri address = new Uri(AuthUrl);
var cookieJar = ReadCookiesFromDisk(COOKIE_FILE);
if (cookieJar.Count == 0)
return false;
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false,
AllowAutoRedirect = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
int timeout = 15000;
var task = client.GetAsync(address.ToString());
Task[] tasks = new Task[1];
tasks[0] = task;
if (Task.WaitAny(tasks, timeout) != -1)
{
// task completed within timeout
// checking for redirect, but this should not happen!!!
HttpResponseMessage response = task.Result;
if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Redirect)
return true;
else
return false;
}
else
{
// timeout logic
return false;
}
}
catch (Exception e)
{
EventLogger.Log(e);
return false;
}
}
Client Authentication Code:
public async Task<string> Login(string data)
{
try
{
Uri address = new Uri(LoginUrl);
HttpContent content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var cookieJar = ReadCookiesFromDisk(COOKIE_FILE);
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false,
AllowAutoRedirect = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
HttpResponseMessage response = await client.PostAsync(address.ToString(), content);
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
if (responseCookies[".ASPXAUTH"] != null)
WriteCookiesToDisk(COOKIE_FILE, cookieJar);
return body;
}
catch (Exception e)
{
return e.ToString();
}
}
Server:
public JsonResult LogOn(string userInfo)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
LogOnModel model = serializer.Deserialize<LogOnModel>(userInfo);
JsonMessage error = null;
if (ModelState.IsValid)
{
try
{
if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
if (WebSecurity.IsConfirmed(model.UserName))
{
if (model.RememberMe)
Response.Cookies[0].Expires = DateTime.Now.AddDays(30);
else
Response.Cookies[0].Expires = DateTime.Now.AddDays(7);
var person = Dc.People.FirstOrDefault(x => x.UserName == model.UserName);
string fullName = string.Empty;
string email = string.Empty;
if (person != null)
{
fullName = string.Format("{0} {1}", person.FirstName, person.LastName);
email = person.Email;
//fill the session to create the session cookie
Session["1"] = 1;
}
var message = new { FailCount = 0, Message = WebSecurity.GetUserId(model.UserName).ToString(), Success = true, SuccessCount = 0, RedirectUrl = "#/conversations/priority", Name = fullName, UserEmail = email, UserHandle = model.UserName, UserAvatar = person.Avatar };
return Json(message);
}
else
{
error = new JsonMessage { FailCount = 0, Message = "Your aren't authorised to login", Success = false, SuccessCount = 0 };
TempData["Error"] = "Your are not authorised to login";
return Json(error);
}
}
else
{
TempData["Error"] = "The user name or password provided is incorrect.";
error = new JsonMessage { FailCount = 0, Message = "The user name or password provided is incorrect.", Success = false, SuccessCount = 0 };
return Json(error);
}
}
catch (Exception ex)
{
TempData["Error"] = ex.Message;
error = new JsonMessage { FailCount = 0, Message = ex.Message, Success = false, SuccessCount = 0 };
}
}
return Json(error);
}
Change following code
HttpResponseMessage response = await client.PostAsync(address.ToString(), content);
to
HttpResponseMessage response = await client.PostAsync(address.ToString(), content).ConfigureAwait(false);
above statement sometime show deadlock issues when using ASync. so when you configure await to false for Async Task, it will work in correct manner.

Try-Catch doesn't show Message Dialog box with await

The following code successfully gets data from a web service and displays it in a Windows 8 desktop app.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");
var info = new List<SampleDataGroup>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var item = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in item)
{
var infoSect = new SampleDataGroup
(
(string)data.Id.ToString(),
(string)data.Name,
(string)"",
(string)data.PhotoUrl,
(string)data.Description
);
info.Add(infoSect);
}
}
else
{
MessageDialog dlg = new MessageDialog("Error");
await dlg.ShowAsync();
}
This does however require an internet connection to work. The app crashes every time there is no internet connection.
How do I write a try catch statement in this code to display a pop up message if the network connection doesnt work?
EDIT:
I am trying to use MessageDialog below, and this stops the app from crashing, but it doesn't bring up the message.
catch (Exception ex)
{
MessageDialog err = new MessageDialog(ex.Message);
}
Don't you need
string errorMessage = string.Empty;
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await
client.GetAsync("http://localhost:12345/api/items");
var info = new List<SampleDataGroup>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var item = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in item)
{
var infoSect = new SampleDataGroup
(
(string)data.Id.ToString(),
(string)data.Name,
(string)"",
(string)data.PhotoUrl,
(string)data.Description
);
info.Add(infoSect);
}
}
else
{
errorMessage = "Error";
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
if (errorMessage != string.Empty)
{
MessageDialog dlg = new MessageDialog(errorMessage);
await dlg.ShowAsync();
}
?

Categories

Resources