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.
Related
We have an app that sends email to person(requestor) selected from a combobox. It only sends one email.
New requirement is that we want to send more than one email to more than one person.
The project owner does not want to replace the current combobox with a listbox. This will require additional database work.
So what was suggested to me for a solution is to add a listbox which is populated with the same information (name objects from the database) as the combobox.
The listbox will be used only when the user want to send email to extra people.
How do I modify the code for this button so that it sends email to the requestor selected in the combobox (which it is currently doing) and also send email to any requestor selected from the listbox?
Before the email is sent, I want to check to make sure that the selected requestor from the combobox is not also selected in the listbox. I do not want the requester to receive two email.
Here is the Listbox which has the same data for the requestor as the combobox.
public async void PopulateAdditionalStaffEmailListBox()
{
List<GetRequestorInfoModel> requestors = new List<GetRequestorInfoModel>();
try
{
requestors = await FTACaseReset.Controllers.RequestorInfoController.GetAllRequestorInfoes();
requestors = requestors.OrderBy(x => x.DisplayName).ToList(); //Has 15 items
//Populate AdditionalStaffEmailListBox
for (int i = 0; i < requestors.Count; i++)
{
ListBoxItem requestor = new ListBoxItem();
requestor.Text = requestors[i].DisplayName;
requestor.Value = requestors[i].RequestorInfoID;
AdditionalStaffEmailListBox.Items.Add(requestor.Text).ToString();
}
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "AdditionalStaffEmailListBox()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here is the code for the button that is currently sending email to requester selected from the combobox
private async void SendEmail(int selectedBatch)
{
string message = "The following records have been prepped for processing. Valid cases will be processed.{0}{1}{2}";
string requestorName = string.Empty;
string requestorEmail = string.Empty;
List<GetCandidateCaseModel> masterCandidateCasesListToDisplay = new List<GetCandidateCaseModel>();
try
{
masterCandidateCasesListToDisplay = await Controllers.CandidateCaseController.GetAllCandidates();
masterCandidateCasesListToDisplay = masterCandidateCasesListToDisplay.Where(x => x.BatchNumber == selectedBatch && x.RejectionReason != null).ToList();
if (masterCandidateCasesListToDisplay.Count > 0)
{
requestorName = masterCandidateCasesListToDisplay[0].RequestorInfo.DisplayName;
requestorEmail = masterCandidateCasesListToDisplay[0].RequestorInfo.Email;
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress("NoReply_FTA#courts.state.mn.us");
//Uncomment after testing June 2019
MailAddress to = new MailAddress(requestorEmail);
mailMessage.To.Add(to);
string ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
mailMessage.Subject = "FTA Case Reset Notice";
mailMessage.Body = message;
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMessage);
MessageBox.Show("An email has been sent to " + requestorName, "Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
MessageBox.Show("No Requestor was found. Unable to send an email.", "Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "SubmitButton_Click()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Its quite difficult understand your code if you dont show your custom classes.
The following code should work but be aware that comparing display names is not the best idea so if you can compare them by some id, do that instead.
private async void SendEmail(int selectedBatch)
{
string message = "The following records have been prepped for processing. Valid cases will be processed.{0}{1}{2}";
string requestorName = string.Empty;
string requestorEmail = string.Empty;
List<GetCandidateCaseModel> masterCandidateCasesListToDisplay = new List<GetCandidateCaseModel>();
try
{
masterCandidateCasesListToDisplay = await Controllers.CandidateCaseController.GetAllCandidates();
var selectedCandidate = masterCandidateCasesListToDisplay.Where(x => x.BatchNumber == selectedBatch && x.RejectionReason != null).ToList();
if (masterCandidateCasesListToDisplay.Count > 0)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
string requestorName0 = selectedCandidate[0].RequestorInfo.DisplayName;
string requestorEmail0 = selectedCandidate[0].RequestorInfo.Email;
MailMessage mailMessage = new MailMessage();
MailAddress to = new MailAddress(requestorEmail);
mailMessage.From = new MailAddress("NoReply_FTA#courts.state.mn.us");
mailMessage.To.Add(to);
mailMessage.Subject = "FTA Case Reset Notice";
mailMessage.Body = message;
mailMessage.IsBodyHtml = true;
string ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
foreach (ListViewItme item in AdditionalStaffEmailListBox.SelectedItems)
{
candidate = masterCandidateCasesListToDisplay.First(x => x.RequestorInfo.DisplayName == item.Value);
requestorName = candidate.RequestorInfo.DisplayName;
requestorEmail = candidate.RequestorInfo.Email;
if (requestorEmail0 == requestorEmail)
{
continue;
}
to = new MailAddress(requestorEmail);
mailMessage.To.Add(to);
ccEmailAddress = Authentication.GetADEmail();
if (ccEmailAddress.Length > 0)
{
MailAddress ccto = new MailAddress(ccEmailAddress);
mailMessage.CC.Add(ccto);
}
MessageBox.Show("An email has been sent to " + requestorName, "Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
smtpClient.Send(mailMessage);
}
else
{
MessageBox.Show("No Requestor was found. Unable to send an email.", "Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "SubmitButton_Click()", ex.Message);
MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
What is going wrong?
I am trying to send an email but I'm getting the error in the title of the question. why doesn't an object be converted to a 'System.Net.Mail.MailMessage'.
private object message;
protected void btnSend_Click(object sender, EventArgs e)
{
String TMess = txtMessageBody.Text;
String TEmail = txtEmail.Text;
String TSub = txtSubject.Text;
//this particular email server requires us to login so
//create a set of credentials with the relevent username and password
System.Net.NetworkCredential userpass = new System.Net.NetworkCredential();
userpass.UserName = "email";
userpass.Password = "password";
//ensure the smtp client has the newly created credentials
client.Credentials = userpass;
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
}
else
{
//create a new email from REPLACE_WITH_USER#gmail.com to recipient#domain.com
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
}
//set the subject of the message, and set the body using the text from a text box
message.Subject = txtSubject.Text;
message.Body = txtMessageBody.Text;
//send the message
client.Send(message);
//clear the message box
//the email has been sent - either by displaying a message (e.g. a literal) or by redirecting them to a 'Message sent' page
txtMessageBody.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
}
var client = new SmtpClient();
var message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
var subject = txtSubject.Text;
var body = txtMessageBody.Text;
message.Subject = subject;
mail.Body = body;
client.Send(message);
At the absolute minimum this should work just fine. Try adding your other code one line at a time and see where it breaks.
the problem lies in your if else loop. If it goes to the if statement ( and not the else statement) your mailmessage object doesn't exist. something that doesn't exist can't be parsed.
you can do it like this
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
return;
}
I have following code for sending an email alert to around 60 users when an extract gets uploaded. However something strange is happening, it is sending to the previous query results not the new ones. The only difference is the quantity of users before it was sending to only a few people now its sending to a larger quantity. But on the code with larger quantity the application seems to not see that it has changed and sends to previous users. Like its cached the query or something. I don't know whats going on. But when I do change it to just one email address it works fine and picks up changes.
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Connection String (SendEmail)
string SendEmail = ConfigurationManager.ConnectionStrings["SendEmail"].ConnectionString;
SqlDataReader reader;
String SendMessage = "SELECT Name, Position, Email FROM AuthorisedStaff Where Position = 'CM' or Position = 'DHOD' or Position = 'HOD'"; //<---- change position before launch
using (SqlConnection myConnection = new SqlConnection(SendEmail))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(SendMessage, myConnection);
ArrayList emailArray = new ArrayList();
reader = myCommand.ExecuteReader();
var emails = new List<EmailCode>();
while (reader.Read())
{
emails.Add(new EmailCode
{
Email = Convert.ToString(reader["Email"]),
Name = Convert.ToString(reader["Name"]),
Position = Convert.ToString(reader["Position"])
});
}
foreach (EmailCode email in emails)
{
//Email Config
const string username = "roll#test.co.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.co.uk", "PTLP"); //address and from name
smtpclient.Host = "omavex11"; //host name for particular email address
smtpclient.Port = 25; //port number for particular email address
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
//change context of message below as appropriate
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Lecturer Payroll details are now available for checking. If any changes need made please notify MIS as soon as possible. </p> <p>Please ensure all Adjustments have also been submitted. All Adjustments not submitted on time will be paid the following month. </p> ";
//smtpclient.EnableSsl = true;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
}
}
}
Try clearing the list first before adding new items/objects
I assume that this
var emails = new List<EmailCode>();
is the list.
I'm trying to do a reset password and recover password function. Therefore i used the smtp way to send the mail. However, i got an error from my try catch.
Error Occured: Failure sending mail.
I'm also not sure which part of my web.config file should i add this connection code
<network host="smtp.gmail.com" enableSsl="true" />
Below is my connection to my Azure database while having the smtp logic.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string uniqueCode = string.Empty;
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
// get the records matching the supplied username or email id.
cmd = new SqlCommand("select * from MemberAccount where nric COLLATE Latin1_general_CS_AS=#nric or email COLLATE Latin1_general_CS_AS=#email", con);
cmd.Parameters.AddWithValue("#nric", Convert.ToString(txtUserName.Text.Trim()));
cmd.Parameters.AddWithValue("#email", Convert.ToString(txtEmailId.Text.Trim()));
dr = cmd.ExecuteReader();
cmd.Dispose();
if (dr.HasRows)
{
dr.Read();
//generate unique code
uniqueCode = Convert.ToString(System.Guid.NewGuid());
//Updating an unique random code in then UniquCode field of the database table
cmd = new SqlCommand("update MemberAccount set UniqueCode=#uniqueCode where nric=#nric or email=#email", con);
cmd.Parameters.AddWithValue("#uniqueCode", uniqueCode);
cmd.Parameters.AddWithValue("#nric", txtUserName.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtEmailId.Text.Trim());
StringBuilder strBody = new StringBuilder();
//Passing emailid,username and generated unique code via querystring. For testing pass your localhost number and while making online pass your domain name instead of localhost path.
strBody.Append("Click here to change your password");
// sbody.Append("&uCode=" + uniqueCode + "&uName=" + txtUserName.Text + ">Click here to change your password</a>");
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("SenderEmailIAddress#hotmail.com", dr["email"].ToString(), "Reset Your Password", strBody.ToString());
//pasing the Gmail credentials to send the email
System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("SenderEmailIAddress#hotmail.com", "SenderPassword");
System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient("smtp.hotmail.com", 587);
mailclient.EnableSsl = true;
mailclient.Credentials = mailAuthenticaion;
mail.IsBodyHtml = true;
mailclient.Send(mail);
dr.Close();
dr.Dispose();
cmd.ExecuteReader();
cmd.Dispose();
con.Close();
lblStatus.Text = "Reset password link has been sent to your email address";
txtEmailId.Text = string.Empty;
txtUserName.Text = string.Empty;
}
else
{
lblStatus.Text = "Please enter valid email address or username";
txtEmailId.Text = string.Empty;
txtUserName.Text = string.Empty;
con.Close();
return;
}
}
catch (Exception ex)
{
lblStatus.Text = "Error Occured: " + ex.Message.ToString();
}
finally
{
cmd.Dispose();
}
}
UPDATE
I just realized why it couldn't work. It did not work as my account information is incorrect
Why this much blah blah codes. Just Try in Simple way.,
For Example:
In your Web.Config / App.Config:
<system.net>
<mailSettings>
<smtp from="Your Email ID">
<network host="Your Host Namecom" defaultCredentials="false" password="*********" userName="Your User Name" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
In Your Code Behind:
private void SendMail(string Address, string Body)
{
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(Address);
mailMessage.Subject = "Your Subject";
mailMessage.IsBodyHtml = true;
mailMessage.Body = Body;
SmtpClient smtpClient = new SmtpClient(); // This will take the Credentioals from the WEB/APP Config
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
Extention.Log(ex.Message + "/=> " + ex.StackTrace);
}
}
Call the Function Like this:
SendMail("To Address Email Id", strBody.ToString());
It Will work :)
I see in your code that you use the hotmail smtp. For my website I also use that server.
If you use those server you must know that your credentials are your hotmail login. The sender of the message must also be the same adres.
I wrote a quick script to send mail and tested it. It worked:
using (var client = new System.Net.Mail.SmtpClient("smtp.live.com", 25))
{
client.Credentials = new System.Net.NetworkCredential("example#hotmail.com", "******");
client.EnableSsl = true;
var from = new System.Net.Mail.MailAddress("example#hotmail.com", "Your name");
var to = new System.Net.Mail.MailAddress("target#example.com", "Receiver name");
var message = new System.Net.Mail.MailMessage(from, to);
message.Subject = "Test mail";
message.Body = "Content";
client.Send(message);
}
If you specify all your SMTP information in code you do not need it in your web.config.
Microsoft smtp (hotmail/live/outlook etc)
Host: smtp.live.com
Port: 587 or if 587 is blocked 25
TSL/SSL: yes
Authentication: Your hotmail/live/outlook account
Sender: Always your hotmail/live/outlook adress
Gmail smtp
Host: smtp.gmail.com
Port: 465
TSL/SSL: yes
Authentication: Your gmail account
Sender: Always your gmail adress
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)