The name 'txtname' doesn't exist in the current context - c#

I am using visual studio 2010. When i run the asp page it shows the errors "The name 'txtname' doest not exists in the current context". I am new in C# programming needs help.
I am using all the defined variables but i am still confused why it is giving errors.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
namespace WebApplication1
{
public partial class contactus : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("myinfo#yahoo.com");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("abc#gmail.com");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = txtName.Text + " : " + txtName1.Text;
msg.Body = txtMessage.Text;
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("abc#gmail.com", "paswword");
client.Credentials = credentials;
//Send the msg
client.Send(msg);
//Display some feedback to the user to let them know it was sent
lblResult.Text = "Your email has been received, you will be contacted soon by our representative if required.";
//Clear the form
txtName.Text = "";
txtName1.Text = "";
txtMessage.Text = "";
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again.";
}
}
}
}

When .cs file name in Code behind attribute does not match , then only this kind of error can occur.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Or it seems that you have copy and pasted the control or code related to it.
This often creates problem in designer file.
You can delete that textbox and once again drag-drop it on your app from toolbar

add runat="server" in the txtName control if it is a regular html control.

I know this is and old question. I got the same problem after copying few divs in a seperate place. This might be useful to anyone in future. Just remove runat="server" attribute of the relevenat tag and again insert it. It worked for me 100%.

Related

Cannot able to send mail from SMTP server using ASP.net with c#

I have created one webpage in ASP.net with C#. In which I have put one button when this button clicks need to send mail. But, when I click on this button getting this exception :-
System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.7.1 : Relay access denied at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button1_Click(Object sender, EventArgs e) in c:\Users\jay.desai\Documents\Visual Studio 2013\WebSites\WebSite2\Default.aspx.cs:line 47
Please refer below code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("serveradmin.dmd#ril.com");
mail.Subject = "Pallet Shortage Emergency";
mail.To.Add("jay.desai#ril.com");
mail.Body ="Only 100 pallets are availabe in ASRS. This is system generated mail do not reply";
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
System.Net.NetworkCredential("serveradmin.dmd#ril.com", "1234");
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
The server error is indicating that it will not relay messages. Usually this means that you need to authenticate with the server before it will allow you to send email, or that it will only accept emails for delivery from specific source domains.
If you are always going to be sending to a single email domain then you can generally use the registered MX server for the domain. In this case (ril.com) the MX server list includes several primary mail servers, but the first one for me is: gwhydsmtp010.ril.com. I'd try that as the target mail server if your website is hosted outside the network that the mail server is on.
Alternatively you can provide SMTP login credentials to the SmtpClient object like this:
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("username", "password");
Logging in to the server will generally solve most 5.7.1 errors.
One final method that might be useful if you have admin rights on the Exchange server is to setup an SMTP connector to allow relay from a specific source address (your web server). I wouldn't recommend this however as any open relay is a Bad Idea(tm).

c# MailMessage: Send mail using default email account

I'm sending emails from my winforms app by using the MailMessage functionality.
I compile the email, save it to disk and then the default mail client will open the mail for the user to verify the settings before hitting Send.
I want to set the 'From' of the email automatically to the default email account as set up in the mail client. How can I do that?
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmailAccount);
mailMessage.To.Add(new MailAddress("recipient#work.com"));
mailMessage.Subject = "Mail Subject";
mailMessage.Body = "Mail Body";
If I leave fromEmailAccount blank I get an error, and if I set it to something like 'test#test.com' the email does not send as the local account does not have permissions to send it via an unknown account.
Get the user information from the OS (If windows 8, 10) them set the from to the user email, see this question: Get user information in Windows 8?
I have tested the following code and this seems to grab the local default mail from address and launches the mail message window, hope it helps:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace testMailEmailUser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Outlook.Application application = new Outlook.Application();
Outlook.AddressEntry mailSender = null;
Outlook.Accounts accounts = application.Session.Accounts;
foreach (Outlook.Account account in accounts)
{
mailSender = account.CurrentUser.AddressEntry;
}
Outlook.MailItem mail =
application.CreateItem(
Outlook.OlItemType.olMailItem)
as Outlook.MailItem;
if (mailSender != null)
{
mail.To = "someone#example.com; another#example.com";
mail.Subject = "Some Subject Matter";
mail.Body = "Some Body Text";
mail.Sender = mailSender;
mail.Display(false);
}
}
}
}

Strings not compatible for email address

I am new to C#. In my verge of learning this language, I made a windows form application application that takes in an email address and a password and sends it to a pre-specified email address. I don't think that I have messed up the data types though I am getting an error The specified string is not in the form required for an e-mail address.
My code is below :
namespace mailTest
{
public partial class Form1 : Form
{
string mailAddress = "lancepreston#gmail.com";
string mailPassword = "123456789";
string SMTP = "smtp.gmail.com";
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage(Email.Text, Password.Text); \\ I get the error on this line
SmtpClient client = new SmtpClient(SMTP);
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(mailAddress,mailPassword);
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);
}
}
}
Screenshot of my form :
MailMessage constructor is defined as below
public MailMessage(string from, string to);
First parameter is from address and second is to address, but you seem to pass password in second parameter. That's why you get the exception.
That particular constructor of the MailMessage class expects the first parameter to be the email address of the sender, and the second parameter to be the email address of the recipient:
http://msdn.microsoft.com/en-us/library/14k9fb7t(v=vs.110).aspx
You are providing a password to the parameter that expects the recipient's email address.
I presume you really want to pass the password in the body of the message.
Take a look at the constructor that populates the body, or set the Body property after initializing a MailMessage:
http://msdn.microsoft.com/en-us/library/5k0ddab0(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.body(v=vs.110).aspx
You have to specify UserName in NetworkCredential , like the following:
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;
See the explanation at:
http://msdn.microsoft.com/en-us/library/system.net.networkcredential.username%28v=vs.110%29.aspx
Also, your MailMessage has wrong parameters (shoud be from/to).
Regards,

Sending Email using SMTP in C#

**It just says " Failure sending mail."
Not sure its the problem with the code or SMTP server ? Please help here is my code, the variables are send through a form and i have confirmed that all variables are ok
SMTP Settings is in Web.config**
<?xml version="1.0"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="newsletter#abc.com">
<network host="mail.abc.com" port="25" userName="newsletter#abc.com" password="abc#!#"/>
</smtp>
</mailSettings>
</system.net>
<system.web>
</system.web>
</configuration>
Code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdSend_Click(object sender, EventArgs e)
{
MailMessage mMailMessage = new MailMessage();
// address of sender
mMailMessage.From = new MailAddress(txtFrom.Text);
// recipient address
mMailMessage.To.Add(new MailAddress(txtTo.Text));
// Check if the bcc value is empty
if (txtBcc.Text != string.Empty)
{
// Set the Bcc address of the mail message
mMailMessage.Bcc.Add(new MailAddress(txtBcc.Text));
}
// Check if the cc value is empty
if (txtCc.Text != string.Empty)
{
// Set the CC address of the mail message
mMailMessage.CC.Add(new MailAddress(txtCc.Text));
} // Set the subject of the mail message
mMailMessage.Subject = txtSubject.Text;
// Set the body of the mail message
mMailMessage.Body = txtBody.Text;
// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal;
// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient();
// Send the mail message
try
{
mSmtpClient.Send(mMailMessage);
}
catch (Exception ex)
{
;//log error
lblMessage.Text = ex.Message;
}
finally
{
mMailMessage.Dispose();
}
}
}
Try using a telnet command to check if you can send a mail.
Start-> type "telnet":
open smtp.server.com 25
Helo smtp.server.com
Mail from:yourAdress#server.com
Rcpt to:yourAdress#server.com
Data
Subject:The life
OMG
.
Quit
If telnet isn't there, add it through add/remove windows features. See :http://technet.microsoft.com/en-us/library/cc771275(v=ws.10).aspx
First, we didn't the specify the SMTP server name:
SmtpClient smtp = new SmtpClient(#"abc.company.com");
Second, after specifying the SMTP server name like the snippet above, Make sure the firewall or Symantec (or some program like that) is not blocking the outbound request.
In your try catch block, you will need to go through all the exceptions. Keep looping until exception.innerexception is null. A more detailed error message will be found in the inner exception to why the mail message failed to be sent. The outer exception and corresponding message will be generic and not that useful.
Some samples can be found here:
Best way to check for inner exception?
Here some Psuedo Code
while (ex != null)
{
//LogThisException(ex);
ex = ex.InnerException;
}

How to use Microsoft.Exchange.WebServices?

i try to use : Microsoft.Exchange.WebServices.dll to use outlook. but connection return error
Error return line:service.AutodiscoverUrl("myusernamek#xxxx.com");
The Autodiscover service could not be located. my codes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace test
{
class Program
{
static void Main(string[] args)
{
try
{
// Connect to Exchange Web Services as user1 at contoso.com.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("myusernamek#xxxx.com", "mypassword", "xxxx.com");
service.TraceEnabled = true;
service.AutodiscoverUrl("myusernamek#xxxx.com");
// Create the e-mail message, set its properties, and send it to user2#contoso.com, saving a copy to the Sent Items folder.
EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("recipientname#xxxx.aero");
message.SendAndSaveCopy();
// Write confirmation message to console window.
Console.WriteLine("Message sent!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadLine();
}
}
}
}
I know this is an old question, but recently wrestled with this and similar looking error (including ISA server). It was fixed with:
service.EnableScpLookup = false;
This was not required when working with an explicit URL, but was when using AutoDiscover
This is a common problem , Autodiscover service error is encountered when this autodiscover service by exchange is down
Resolution is to provide actual URL for exchange location , rather than autodiscovering it.
This solved my same issue.
The code suggest that you have an Exchange 2007 server... Is it properly configured for using the Autodiscover features? Confirm that you can ping autodiscover.XXXX.com and view https://autodiscover.XXXX.com in a web browser.
Alternately, you may need to use your internal domain name for autodiscovery and login. For example, in my office the external email addresses are on a domain like CompanyX.com, but the internal Active Directory domain is like CompanyX.local, and we do not have autodiscover on the open Internet, so my EWS needs to locate Autodiscover.CompanyX.local.
this is an old post but maybe someone will need it.
do not use auto discover, it is rly slow.
how to find your exchange url:
-open your outlook application and connect to your exchange
-hold Ctrl key and right click on the outlook icon in the system tray
-select "test e-mail auto configuration"
-click the test button
-look for the following line:
oh and to use the url you trop that extra line of code:
service.Url = new Uri("your url here");
try these concept:
private static ExchangeService getService(String userEmail, String login, String password, String hostName)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
AutodiscoverService auservice = new AutodiscoverService(hostName);
if (auservice.ServerInfo != null)
{
try
{
service.AutodiscoverUrl(userEmail, RedirectionUrlValidationCallback);
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
}
}
else
{
service.Url = new Uri("https://" + hostName + "/EWS/Exchange.asmx");
}
service.UseDefaultCredentials = true;
if (service.ServerInfo == null)
{
service.Credentials = new WebCredentials(login, password);
}
return service;
}

Categories

Resources