I used this one to send the email, but when I submit, it was showing me "Line 41: smtp.Send(msg);" error. I do not know what's wrong with this. Thanks for the help!
public partial class Contact : Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("xxxxx#gmail.com");
msg.To.Add("xxxxx#hotmail.com");
msg.Subject = txtSubject.Text;
msg.Body = txtFirstName.Text + " " + txtLastName.Text + "'s phone number is: " + txtPhone.Text + ". <br />" + "Email Address is: " + txtEmail.Text + "Message: <br />" + txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "xxxxx#gmail.com";
NetworkCred.Password = "xxxxx";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(msg);
lblMessage.Text = "Email has been successfully sent!";
}
}
Stack Trace:
[SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at]
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) +1844406
System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) +46
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) +88
System.Net.Mail.SmtpClient.Send(MailMessage message) +1856
XinNing_Web.Contact.btnSubmit_Click(Object sender, EventArgs e) in E:\Projects\ASP.NET\XinNing_Web\XinNing_Web\Contact.aspx.cs:41
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9767618
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1738
Allow less secure app to true in your gmail account from which your are trying to send the mail.
Go to my account -> sign-in & security -> Allow less secure app( at bottom of the page).
Some time due to this error occured.
Related
I have an ASP.NET 4.5 application with a separate class library for accessing the Google analytics data. Every try to use the common methods (loading the certificat from .p12 file) ends in an "internal error" (the file will be found!) in 3rd line (Dim certificat...)
Dim scopes As String() = New String() {AnalyticsService.Scope.Analytics}
Dim serviceAccountEmail = "info#xxx.biz"
Dim certificate = New X509Certificate2(System.Web.HttpContext.Current.Server.MapPath("Certificates/MyDashboard-b335c24b1a76.p12"), "notasecret", X509KeyStorageFlags.Exportable)
Dim credential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {.Scopes = scopes}.FromCertificate(certificate))
Dim service = New AnalyticsService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = "MyDashboard" _
})
Dim MyRequest As DataResource.GaResource.GetRequest = service.Data.Ga.Get("ga:44582845", "2016-01-01", "2016-01-01", "ga:sessions")
MyRequest.MaxResults = 1000
Dim MyResult As GaData = MyRequest.Execute()
[CryptographicException: Interner Fehler.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +307
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +92
GoogleAnalyticsClient.Class1..ctor() in P:\Google Analytics\GoogleAnalyticsClient\Class1.vb:59
preisvergleich.Statistik.Page_Load(Object sender, EventArgs e) in \web\Webs\AFFILIATE 2.0\preisvergleich\Statistik.aspx.vb:16
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
Is there any possibility to access the analytics data without the certificate (I think it was in former times)?
BR Jan
I want to send mail using ASP.NET with this code:
public void Semail(string subject, string messageBody, string toAddress)
{
MailMessage mail = new MailMessage();
mail.To.Add(toAddress);
//mail.To.Add("amit_jain_online#yahoo.com");
mail.From = new MailAddress("noreplykaramaoozi#eesharif.edu");
mail.Subject = subject;
string Body = messageBody;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "sina.sharif.ir"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("noreplykaramaoozi#eesharif.edu", "******");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
But after executing i got this error :
Syntax error, command unrecognized. The server response was: Dovecot ready.
This is the stacktrace
[SmtpException: Syntax error, command unrecognized. The server response was: Dovecot ready.]
System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +2176152
System.Net.Mail.SmtpClient.Send(MailMessage message) +2188821
Novitiate.fa.Register.btnLogin_Click(Object sender, EventArgs e) +2948
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
There might be issue with SMTP Server.
Try with GMAIL Settings, if mail is working with GMAIL server, then most probably there is issue with your Mailing Server.
It looks like you are using POP3 or IMAP server not SMTP Server, please check configuration of your Server
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
When using gmail smtp server and ssl be sure to use 587 port instead of 465, this solved the issue for me.
I am trying to send an email to the user's account when the user clicks send button. But I am getting the above error. Below is my sendClick code.
protected void btnsendCode_Click(object sender, EventArgs e)
{
try
{
if (txtemail.Text != "")
{
Random rd = new Random();
veri = rd.Next(1000, 10000);
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress(txtemail.Text.ToString()));
mm.From = new MailAddress("xxx#yyy.in", "Verification Mail");
mm.Body = "Your Verification Code is - " + veri.ToString();
mm.IsBodyHtml = true;
mm.Subject = "Verification mail";
SmtpClient smcl = new SmtpClient();
smcl.Host = "smtp.gmail.com";
smcl.Port = 587;
smcl.Credentials = new NetworkCredential("xxx#yyy.in", "xxx");
//smcl.EnableSsl = true;
smcl.Send(mm);
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Verification Code sent to your Email ID! Please Check your Email!!');", true);
txtverify.Enabled = true;
btnsendCode.Text = "Send Code Again";
lblmsg.Visible = false;
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "Please enter Email ID!!";
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
lblmsg.Focus();
}
}
catch (WebException we)
{
lblmsg.Visible = true;
lblmsg.Text = we.Message.ToString();
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
}
}
Stack Trace
[FormatException: The specified string is not in the form required for
an e-mail address.]
System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(String
data, Int32 index) +1475945
System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32&
index) +135 System.Net.Mail.MailAddressParser.ParseAddress(String
data, Boolean expectMultipleAddresses, Int32& index) +99
System.Net.Mail.MailAddressParser.ParseAddress(String data) +23
System.Net.Mail.MailAddress..ctor(String address, String displayName,
Encoding displayNameEncoding) +220
System.Net.Mail.MailMessage..ctor() +130
events.btnsendCode_Click(Object sender, EventArgs e) in
d:\inetpub\vhosts\marpallichande.in\httpdocs\Test\events.aspx.cs:101
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9552874
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Which part I am committing mistake and need to correct it?
The reason it fails is using the empty constructor without the mail settings to match:
MailMessage mm = new MailMessage();
The empty constructor relies on:
<system.net>
<mailSettings>
<smtp from="report#company.com" />
</mailSettings>
</system.net>
in your app or web.config file. So either use the constructor that expects a from and to address, or add that node to your app/web.config file.
I firmly believe this is a bug in the .Net framework, because we were able to create new MailMessage() objects and then assign the "from" later on, but in .Net 4.0 and under certain conditions—which I still don't fully understand—this fails. I welcome being corrected of course, but for now, this seems like an oversight.
So some of our customers never encountered this issue, but to fix it we had to add that dummy setting to the web.config files.
I had a similar problem with getting [FormatException: The specified string is not in the form required for an e-mail address.] too. My problem was with this code:
void SendMail(string destinationEmail)
MailMessage message=new MailMessage("mytestmail#test.com",destinationEmail);
SmtpClient mailClient = new SmtpClient("mail.test.com", 587);
mailClient.Credentials = new System.Net.NetworkCredential("mytestmail", "pswd");
try{
mailClient.Send(mail);
}
catch (Exception ex){...}
As you can see I just tried and caught only sending part. But this problem was thrown from MailMessage constructor. I would have never guessed that a constructor would throw an exception. So I just tried this code independently:
MailMessage mail = new MailMessage("test", "test");
The result of this code is [FormatException: The specified string is not in the form required for an e-mail address.]. If you try this:
MailMessage mail = new MailMessage("", "");
you'll get ArgumentException: The parameter 'from'(or 'to') cannot be an empty string.
So what you need to do in these kind of cases is you include the MailMessage construction part in the try catch block too and make sure that the exception you catch covers exception types that MailMessage constructor might throw, in this particular case, FormatException. Although I hate cathcing the Exception class, in this case it seems to be a perfect fit.
My question may be duplicate one, but i didn't got a proper solution for my problem.That's why i am asking.
I have a asp website.I am using smtpclient to send messages.My code is working fine with gmail settings.But in the production server they are using Bellnetwork's(smtp10.on.aibn.com) mailing server.They are using port 25 and also not using SSL(email provider doesn't support SSL).But the same mail settings was running fine for the last 2-3 years,but now when we send some messages from our site(production) 1 or 2 fails to send out and others will send out successfully.The strange thing is there was no problem for the last 3years.I am getting the following errors for the failed mails.
Exceptions:
1.
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
2.
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
3.
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 67.69.240.69:25
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 67.69.240.69:25
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
my code:
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
return true;
}
catch (SmtpException ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try failed : " + ee.ToString(),"");
Log.WriteSpecialLog("status code : " + ee.StatusCode, "");
}
}
This code is working for me
public static string sendMail(string fromEmail, string toEmail, string subject, string body, string Name, string bcc="" , string replyTo="")
{
MailMessage mailer = new MailMessage
{
IsBodyHtml = true,
From = new MailAddress(fromEmail, "yoursite.com"),
Subject = subject,
Body = body,
BodyEncoding = Encoding.GetEncoding("utf-8")
};
mailer.To.Add(new MailAddress(toEmail, toEmail));
//
if (!string.IsNullOrEmpty(bcc))
{
mailer.Bcc.Add(bcc);
}
//
if (!string.IsNullOrEmpty(replyTo))
{
mailer.Headers.Add("Reply-To", replyTo);
}
//
AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(body, "<(.|\\n)*?>", string.Empty), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
mailer.AlternateViews.Add(plainView);
mailer.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SMTPserver"]);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
NetworkCredential basicAuthenticationInfo = new NetworkCredential(ConfigurationManager.AppSettings["passMail"], ConfigurationManager.AppSettings["passKey"]);
smtp.UseDefaultCredentials = false;
smtp.Credentials = basicAuthenticationInfo;
smtp.EnableSsl = false;
smtp.Port = ConfigurationManager.AppSettings["Port"];
//
try
{
smtp.Send(mailer);
return "Email sent successfully !";
}
catch (Exception ex)
{
return "Failure in Email Message= !" + ex.message;
}
}
i have been designing a web page in asp.net and my project is successful. and i published my web application.However, below error occurs.How can I clear it?
Server Error in '/sarav' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web >request. Please review the stack trace for more information about the error and where it >originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Login.btnLogin_Click(Object sender, EventArgs e) +155
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
How to clear error
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection Cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != null)
{
constr = ConfigurationManager.ConnectionStrings["PhotostudioConnectionString"].ConnectionString;
Cnn.ConnectionString = constr;
try
{
if (Cnn.State != ConnectionState.Open)
Cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = Cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UspGetDataUsrmast";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#usrname", txtUsername.Text);
cmd.Parameters.AddWithValue("#passwrd", txtPassword.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
// cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new ApplicationException("!!! An Error Occurred While Inserting Record. " + ex.Message);
}
finally
{
da.Dispose();
cmd.Dispose();
Cnn.Close();
Cnn.Dispose();
}
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Login Successfully";
// da.Dispose();
// cmd.Dispose();
// Cnn.Close();
// Server.Transfer("Home.aspx");
Response.Redirect("PhotosettingsReport.aspx");
}
else
{
Msg.Text = "Login Failed";
}
}
}
}
Without seeing the code, it's impossible to even guess as to what object is throwing this error.
Run the website in Visual Studio in debug mode (F5), and put a breakpoint at btnLogin_Click. When you click the button, it will break and allow you to step into the code. Step through the code until you find the line that is throwing the exception - that is the object that is null.
You're either trying to access something declared in the method that has not been initialized, or an object outside the method that has not been initialized.
Stepping through the code will quickly show you what's wrong.
UPDATE
I'd check txtUserName and txtPassword to be sure they have values. Also, are you sure you're getting results into the ds.Tables[0]? Calling Rows.Count on ds.Tables[0] could also result in that error if there are no tables.
Also, check your Web.config file - make sure that "PhotostudioConnectionString" is spelled correctly, including the case of the letters.
Why are you checking for IsValid != null? I think if (!IsValid) would be more proper. IsValid will either be true or false, it will never be null, so your code will always pass that check.