When working locally it works fine, but when publishing the site, the mail function doesn't work. I suspect that the issue might lie with SmtpClient, but I am not sure. Does anyone know if there is a difference in how the network acts when running over the network vs locally?
My code:
public ActionResult SendMail(EmailModel model)
{
string host = ConfigurationManager.AppSettings.Get("SMTPHOST");
int port = Convert.ToInt16(ConfigurationManager.AppSettings.Get("SMTPPORT"));
string receiver = ConfigurationManager.AppSettings.Get("TOADDRESS");
string password = ConfigurationManager.AppSettings.Get("PASSWORD");
SmtpClient smtp = new SmtpClient(host, port);
smtp.Credentials = new NetworkCredential(receiver, password);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
MailMessage mailMsg = null;
var status = new HttpStatusCode();
try
{
if (ModelState.IsValid)
{
mailMsg = new MailMessage(model.from, receiver, model.subject, model.body);
smtp.Send(mailMsg);
return PartialView("_About");
}
else
{
status = HttpStatusCode.BadRequest;
}
}
catch (Exception ex)
{
status = HttpStatusCode.BadRequest;
SendInfoMail("address", "address", "Exception", ex.ToString());
}
return new HttpStatusCodeResult(status);
}
I think the code throws an exception, but since this only happens when the site is published, I can't debug it.
Related
Hi when i use the below code in angular api project my requests are not getting saved and i am gettign this following error. And when i comment the code to send mail everything is working fine
ERROR in console
polyfills POST net::ERR_CONNECTION_RESET
And code to send mail
public async Task SendEmail(string email, string subject, string firstName, string contact)
{
try
{
string message = BuildMessageBody(firstName, email, contact);
using (var client = new SmtpClient())
{
var networkCredential = new NetworkCredential
{
UserName = _configuration["Email:Email"],
Password = _configuration["Email:Password"]
};
client.UseDefaultCredentials = false;
client.Credentials = networkCredential;
client.Host = _configuration["Email:Host"];
client.Port = int.Parse(_configuration["Email:Port"]);
client.EnableSsl = true;
using (var emailMessage = new MailMessage())
{
emailMessage.To.Add(new MailAddress(email));
emailMessage.CC.Add(new MailAddress("my cc adddress"));
emailMessage.From = new MailAddress(_configuration["Email:Email"]);
emailMessage.Subject = subject;
emailMessage.Body = message;
emailMessage.IsBodyHtml = true;
emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
emailMessage.SubjectEncoding = System.Text.Encoding.Default;
emailMessage.ReplyToList.Add(new MailAddress(_configuration["Email:Email"]));
client.SendCompleted += (s, e) => {
client.Dispose();
emailMessage.Dispose();
};
await client.SendMailAsync(emailMessage);
}
}
await Task.CompletedTask;
}
catch (Exception ex)
{
_appLogger.CreateLog("SendEmail - " + ex.Message);
}
}
Any idea why this behaviour???
When I run my application locally on localhost, the e-mail is sent out successfully with no exceptions. But when I publish the application and try to re-create the e-mail it does not send the e-mail nor sends the View with the corresponding error.
try
{
using (var mail = new MailMessage())
{
const string email = "*******#gmail.com";
const string password = "*********";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress("*******#gmail.com");
mail.To.Add(new MailAddress("email#email.com"));
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
return View(status);
}
else
{
return View(status);
}
}
}
catch (SmtpException Se)
{
// handle exception here
return View(Se);
}
catch (Exception ex)
{
return View(ex);
}
The error message is not displayed here, however, it is possible that is a client authentication error.
Please try:
Login into your gmail account
Allow the IP of your hosting under gmail settings
Retry sending the email
Another thing to note, you do not need to try .. finally on your MailMessage() object. Since it is already wrapped in a using statement, when it reaches the end of the using block is will dispose it for you and any errors will get caught in your outer try catch block.
Remove all that exception handling, and try again. Find out what the error is, then go from there.
I suspect the reason youre having a hard time is b/c of the way you have your try/catch's set up. The inner try/catch strikes me as being a little odd.
I am unable to connect to the frontier mail server with the following code. I get the message "Unable to connect to remote server". I am running the program using C# on my local computer.
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.frontier.com");
mail.From = new MailAddress(emailaddress);
mail.To.Add("xxxx#frontier.com");
mail.Subject = thistitle;
mail.Body = thisdescription;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(thisimage);
mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "xxxxxxx");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("Mail sent");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Email Error Message");
}
Can anyone tell if I have the correct parameters for Frontier mail? I know they use Yahoo but I tried that also with no success. Isn't it possible to run a mail server from my local machine? Any help is appreciated.
just try remove this code SmtpServer.EnableSsl = true;
Does your ISP block SMTP traffic? (this is often the case for non-commercial accounts).
If not... rewrite you code closer to this:
try
{
using (var attachment = new Attachment(thisimage))
using (var mail = new MailMessage())
{
mail.From = new MailAddress(emailaddress);
mail.To.Add("xxxx#frontier.com");
mail.Subject = thistitle;
mail.Body = thisdescription;
mail.Attachments.Add(attachment);
using (var client = new SmtpClient("smtp.frontier.com"))
{
client.Port = 25;
client.Credentials = new System.Net.NetworkCredential("username", "xxxxxxx");
client.EnableSsl = true;
client.Send(mail);
}
}
MessageBox.Show("Mail sent");
}
catch (SmtpException ex)
{
// go read through https://msdn.microsoft.com/en-us/library/swas0fwc(v=vs.110).aspx
// go read through https://msdn.microsoft.com/en-us/library/system.net.mail.smtpexception(v=vs.110).aspx
}
#if DEBUG
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Email Error Message");
}
#endif
}
...and run it in a debugger and look at what the SmtpException is reporting. There are myriad reasons why you may fail a connection.
Im unable to comment so I will type my comment as an answer. Are you able to use ImapClient instead of SmtpClient ? With Imap, you can do some authenticating processes. Could be the issue, it only looks like you are signing in. For Imap I do this:
using (var clientTest = new ImapClient())
{
clientTest.Connect("xxxx#frontier.com");
clientTest.AuthenticationMechanisms.Remove("XOAUTH");
clientTest.Authenticate(eMail, pw);
bIsConnected = clientTest.IsConnected;
if (bIsConnected == true)
{
/// Insert Code here
}
}
When I remove the comment "//stmp.timeout" it gives timeout error. What should I do to fix that?
Here is my code:
public ActionResult Index(EmailModel model)
{
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 180;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("sheikh.abm#gmail.com ","somepassword");
//smtp.Timeout = 20000;
}
try
{
smtp.Send("sheikh.abm#gmail.com",model.To, model.Subject, model.Message);
return View("Index");
}
catch (Exception ex)
{
Console.WriteLine(ex); //Should print stacktrace + details of inner exception
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
return View("Index");
In this line
smtp.Credentials = new NetworkCredential("sheikh.abm#gmail.com ","somepassword
there is a space after gmail.com. This could prevent the login to gmail. Remove it.
Also, I think that the port used to send mail to gmail is 465 for SSL or 587 for TLS/STARTTLS.
smtp.Port = 465;
this is driving me absolutely crazy. I am trying to send an email through a web service written in C# through GoDaddy's servers (smtp.secureserver.net) but for some reason it's not working. Here's my code:
public static void SendMessage(string mailFrom, string mailFromDisplayName, string[] mailTo, string[] mailCc, string subject, string body)
{
try
{
using (SmtpClient client = new SmtpClient("smtpout.secureserver.net"))
{
client.Credentials = new NetworkCredential("myemail#mydomain.com", "mypassword");
client.EnableSsl = true;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
string to = mailTo != null ? string.Join(",", mailTo) : null;
string cc = mailCc != null ? string.Join(",", mailCc) : null;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(mailFrom, mailFromDisplayName);
mail.To.Add(to);
if (cc != null)
{
mail.CC.Add(cc);
}
mail.Subject = subject;
mail.Body = body.Replace(Environment.NewLine, "<BR>");
mail.IsBodyHtml = true;
client.Send(mail);
}
}
catch (Exception ex)
{
// exception handling
}
}
string[] mailTo = { "mytestaddress#gmail.com" };
SendMessage("myemail#mydomain.com", "Test Email", mailTo, null, "Secure Server Test", "Testing... Sent at: " + DateTime.Now);
GOT IT!!! Need to remove the line "client.EnableSsl = true;" because godaddy does not accept secure connections.
I had a similar issue. In my case setting the value of client object's .Port public property was the problem.
Right now, I am not setting that value at all and emails arrive quickly, even with attachments.