Mail Code Issue(It works time to time) - c#

Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}

After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);

Related

SmtpClient exception not stepping into SmtpFailedRecipientsException

I am trying to show an error message for failed recipients in my asp.net webpage. For some reason the code is not stepping into the SmtpFailedRecipientException:
SmtpClient client = new SmtpClient("smtp.server.com", 25) { Credentials = new NetworkCredential("any#one.com", "123456") };
using (var message = new MailMessage { })
{
message.From = new MailAddress(salesPersonDropDownList.SelectedItem.Text);
message.To.Add(mailToTextBox.Text);
message.CC.Add(mailToCCTextBox.Text);
message.CC.Add(mailToCCTextBox2.Text);
message.CC.Add(mailToCCTextBox3.Text);
message.Subject = mailSubjectTextBox.Text;
message.Body = mailBodyTextBox.Text;
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
string strSmtpFailedRecipientsException = "test";
}
catch (Exception ex)
{
string strException = "test";
}
}
The code is stepping properly into the the second "catch" but for some reason no into the SmtpFailedRecipientsException. Anyone can tell what I am doing wrong?
Thanks in advance
I found the problem by myself.
The SmtpFailedRecipientsException is for exceptions with two or more failed recipients - and in my case I always had only one failed recipient.
For one failed recipient I had to use the SmtpFailedRecipientException.

Forgot Password in windows form c#

In the code below: I want to warn a user when he/she tries to enter an email which is (is not) associated with the database. When I type something is not in my database, it says "Your record is not in our database". But when I enter a valid email it says: input string was not in a correct format
so this line code doesnt work: smtpClient.Send(message);
string randomCode = "";
public static string to;
public ForgotPassword()
{
InitializeComponent();
}
private void btn_EmailSend_Click(object sender, EventArgs e)
{
string from, pass, messagebody;
#region Generating random code
Random ran = new Random();
string randText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int Length_randText = randText.Length;
for (int i = 0; i < 5; i++)
{
randomCode += randText[ran.Next(Length_randText)];
}
#endregion
MailMessage message = new MailMessage();
to = txt_Email.Text;
from = "------";
pass = "------";
messagebody = "You have requested to reset your password. Enter this \"" + randomCode + "\" - code to change your password";
message.To.Add(to);
message.From = new MailAddress(from);
message.Body = messagebody;
message.Subject = "Password resetting request";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential(from, pass);
try
{
using (DALC.GetConnection())
{
SqlCommand cmd = new SqlCommand("select email from loginuser where email = '" + to + "'", DALC.con);
object result = cmd.ExecuteScalar();
if (Convert.ToInt16(result)>0)
{
smtpClient.Send(message);
MessageBox.Show("I have sent your resetting code to you email. Check your inbox :)", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Your record is not in our database");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You actually shouldn't do that, this is considered bad practice. A malicious user should never be able to guess a valid Email address (which in your case he would be able to).
You should only give the user an Email with a password-reset if he/she enters their Email address correctly. Even if the Email address is not in your database only a message without data-leakage should appear, i.e. "An Email to reset your password has been sent to your address".
The same issue should be applied to a login: If the login fails a user should only receive a message that doesn't distinguish from the name / password, something like "You have entered an invalid username or password".
See also this question for more information.

HTML tags and attributes defect client from receiving email using SmtpClient via anonymous account

I am cracking my head to find a solution for that strange behavior.
I have made a lot of tests and experiments and tried to play around with my code but with no success.
Server: Windows service on windows server 2012 .net framework 4.0.
Client: windows 7 os, outlook 2010.
Problem: html tags and \ or attributes inside the message body are affecting client from receiving emails and no exception is thrown on the server.
there are several cases that html inside the body message is preventing from the client to receive email to his outlook inbox.
Example: if i am calling SendHtmlEmail() like that everything works fine as expected:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl><br/>test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
but if i am removing the <br/> tag, the client is not receiving email and no exception is thrown:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl> test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
another example is using the dir attribute:
"<body dir=rtl> test </body>" // not working
"<body ><br/>test</body>" // working
"<div dir=rtl> test </div>" // not working
"<div ><br/>test</div>" // working
I have tried to change Encoding of the body but nothing helps. also, because no exception is raised I assume the problem is on client side(?) (outlook 2010, windows 7 os).
Thank you.
Server code:
public static bool SendHtmlEmail(string _subject, string _body,
string _to, string _cc = null,
string _DisplayName = "מערכת ניהול פרויקטים", string _FileName = null,bool Isanonymous = true)
{
try
{
MailMessage msg = new MailMessage();
// from
if (Isanonymous == false)
msg.From = new MailAddress("pmsapp#partner.co.il");
else
msg.From = new MailAddress("PmsApplication#partner.co.il", _DisplayName);
// to
foreach (var address in _to.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.To.Add(address);
}
// cc
if (_cc != null && _cc.Contains("#"))
{
foreach (var address in _cc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.CC.Add(address);
}
}
msg.Subject = _subject;
msg.Body = _body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
if (Isanonymous==false)
client.Credentials = new System.Net.NetworkCredential("xxxxx", "xxxxxxx");
client.Port = 25;
client.Host = ConfigurationManager.AppSettings["Exchange.SmtpServerName"];
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
return true;
}
catch (Exception ex)
{
string error = ex.ToString(); // TODO: write to database
return false;
}
}

Getting email address from text box and send it

if (txtEmail.Text != null)
{
try
{
SmtpClient sc = new SmtpClient("localhost", 587);
sc.Host = "smtp.gmail.com";
sc.Credentials = new NetworkCredential("MyEmail#gmail.com",
"MyPassword");
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.EnableSsl = true;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("MyEmail#gmail.com");
mailMessage.Subject = "Sending Test";
mailMessage.Body = "this is a test message your UserName is"
+ txtUserName.Text;
mailMessage.IsBodyHtml = true;
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
sc.Send(mailMessage);
lblMessage.Text = "Mail send...";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
else
{
lblMessage.Text = "you should enter your email address";
}
Alright first of all sorry about my weak English language, however i read lots of articles about how to send an E-mail with C# and i know how to do it...
But my problem is when I want to send E-mail that entered to a text box and I put for example
(E-mailAddress.text) into a MailAddress or MailMessage.Add,
it threw me an exception that says
(The parameter 'addresses' cannot be an empty string. Parameter name: addresses)
and shows me the MailAdress or MailMessage object that filled with E-mailAddress.text instead with a string like "abc#yahoo.com" and even in further i'm not capable to send the E-mail ... if there is any help i'd be so glad
First i would change
txtEmail.Text != null
to
!string.IsNullOrEmpty(txtEmail.Text)
Then i would try to do it this way:
mailMessage.To.Add(new MailAddress(txtEmail.Text.Trim()));
instead of
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
Also i would implement a method to validated the entered email address to avoid invalid addresses :)
Check for:
if (txtEmail.Text.Trim() != String.Empty)
instead of
if (txtEmail.Text != null)

Return message after form is submitted

I am sorry if this has been posted before. I have searched many websites and forms to fix it but I can not get it. I have a simple contact form that allows potential customers to fill out their info click submit and then email a copy of what they inputted to us. I have the email part working fine. However, the part that's not working is message after the form is submitted. I'm try to use a try and catch to display a message when they submit or a err message when it didn't work. Not sure why it is not working. Thank you for the help. My controller code is below.
public ActionResult ContactForm()
{
return View();
}
public ActionResult Message()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactForm(ContactModel emailModel)
{
if (ModelState.IsValid)
{
bool isOk = false;
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("no-reply#bobcravens.com", "Website Contact Form");
msg.To.Add("thovden#hovdenoil.com");
msg.Subject = emailModel.Subject;
string body = "Name: " + emailModel.Name + "\n"
+ "Email: " + emailModel.Email + "\n"
+ "Website: " + emailModel.Website + "\n"
+ "Phone: " + emailModel.Phone + "\n\n"
+ emailModel.Message;
msg.Body = body;
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtpout.server.net", 25);
NetworkCredential Credentials = new NetworkCredential("thovden#hovdenoil.com", "****");
smtp.Credentials = Credentials;
smtp.Send(msg);
msg.Dispose();
isOk = true
ContactModel rcpt = new ContactModel();
rcpt.Title = "Thank You";
rcpt.Content = "Your email has been sent.";
return View("Message", rcpt);
}
catch (Exception ex)
{
}
// If we are here...something kicked us into the exception.
//
ContactModel err = new ContactModel();
err.Title = "Email Error";
err.Content = "The website is having an issue with sending email at this time. Sorry for the inconvenience. My email address is provided on the about page.";
return View("Message", err);
}
else
{
return View();
}
}
}
The problem is that view that you return:
return View("Messgae", err):
You should return the same view after error on "postback", with the invalid model
return View(err);
One time you call that Message view with MessageModel and in this line you called it with ContactModel, so there must be an error over here...
Side notes:
You're catching the Global Exception exception it isn't good practice. Not every exception you can and should handle.
You have an isOK flag that doesn't do a thing.
Move the exception Handel inside the catch block, not afterwards
Updated based on the comments:
Instead of return View you should Redirect:
return RedirectToAction("Message", err);
return RedirectToAction("Message", rcpt);
public ActionResult Message(ContactModel model)
{
return View(model);
}
I would start by emitting the exception so that you can figure out exactly what went wrong. Additionally, you might want to step through the code.

Categories